NODEJS writeStream error

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);

In the above code i'm tring to accept input from the HTML form using the POST method and pipe the same into the write stream of a file , but i'm not able to achieve and the following error is being displayed

{ [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' }

Whats going wrong , what modifications should i do so that i could successfully redirect the data from POST into a file ?? i read this related post Node.js EBADF error when writeing file using writable stream

But still couldnt find a way out , I'm a NODEJS newbie, please help me out .thank you...

Your error is because after the first time req.pipe(fs); runs when the pipe completes it closes the WriteStream fs, every req.pipe(fs); after the first is trying to write to a closed FD, thus the EBADF.

You either need to recreate the WriteStream or use the data event of the req directly rather than using pipe. But either way, you have a serious concurrent issue. You should most likely create new a WriteStream to a distinct file for each request.

By default end() is called on the destination when the source stream emits end, so that destination is no longer writable. Pass { end: false } as options to keep the destination stream open.

You should simply do :

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

and your errors will go away.