NODEJS writeStream错误

时间:2013-02-23 00:59:51

标签: node.js

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表单的输入并将其输入到文件的写入流中,但是我无法实现并且正在显示以下错误< / p>

{ [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 个答案:

答案 0 :(得分:2)

默认情况下,当源流发送结束时,在目标上调用end(),以便该目标不再可写。传递{end:false}作为保持目标流开放的选项。

你应该这样做:

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

你的错误就会消失。

答案 1 :(得分:1)

您的错误是因为在管道完成后第一次运行req.pipe(fs);后,它会在第一次WriteStream fs之后关闭req.pipe(fs); EBADF。关闭FD,因此WriteStream

您需要重新创建data或直接使用req的{​​{1}}事件,而不是使用管道。但不管怎样,你有一个严重的并发问题。您应该为每个请求创建一个新的WriteStream到不同的文件。