2013-02-23 30 views
0
var http = require('http'); 
var fs = require('fs').createWriteStream('file1');; 

http.createServer(function(req, res) { 
    // This opens up the writeable stream to `output` 


    // This pipes the POST data to the file 
    req.pipe(fs); 

    // After all the data is saved, respond with a simple html form so they can post more data 
    req.on('end', function() { 
    res.writeHead(200, {"content-type":"text/html"}); 
    res.end('<form method="POST"><input name="test" /><input type="submit"></form>'); 
    }); 

    // This is here incase any errors occur 
    fs.on('error', function (err) { 
    console.log(err); 
    }); 
}).listen(8080); 

在上面的代碼即時特林接受來自使用POST方法和管相同的到一個文件的寫入流的HTML表單輸入,但我不能夠實現和正在顯示以下錯誤的NodeJS writeStream錯誤

{ [Error: EBADF, close] errno: 9, code: 'EBADF' } 
{ [Error: EBADF, close] errno: 9, code: 'EBADF' } 
{ [Error: EBADF, close] errno: 9, code: 'EBADF' } 
{ [Error: EBADF, close] errno: 9, code: 'EBADF' } 
{ [Error: EBADF, close] errno: 9, code: 'EBADF' } 
{ [Error: EBADF, close] errno: 9, code: 'EBADF' } 
{ [Error: EBADF, close] errno: 9, code: 'EBADF' } 
{ [Error: EBADF, close] errno: 9, code: 'EBADF' } 
{ [Error: EBADF, close] errno: 9, code: 'EBADF' } 

出現什麼問題了,應該做什麼修改以便我可以成功地將POST數據重定向到文件中?我讀到這有關的職位Node.js EBADF error when writing file using writable stream

但仍無法找到出路,我是一個新手的NodeJS,請幫助我。謝謝你......

回答

2

默認情況下,當源流發出結束時,將在目標上調用end(),以便目標不再可寫。通過{end:false}作爲選項以保持目標流處於打開狀態。

你應該簡單地做:

req.pipe(fs, { end: false }); 

,你的錯誤便會自行消失。

1

你的錯誤是因爲第一次後req.pipe(fs);運行時,管道完成後關閉WriteStreamfs,每隔req.pipe(fs);後首先嚐試寫入封閉的FD,因此EBADF

您需要直接重新創建WriteStream或使用reqdata事件,而不是使用管道。但無論如何,你有一個嚴重的併發問題。您應該很可能爲每個請求創建一個新的WriteStream到不同的文件。