Search code examples
node.jsexpressasync.jsgridfs-stream

Node res.write all data before res.end() is called


Trying to write all files and then end response, but it somehow calls res.end before all writing is finished. How I can fix it, to do all the writing, and after that call res.end()?

Error msg atm: Error: write after end

app.get('/api/upload', function (req, res) {
  gfs.files.find({}).toArray(function (err, files) {

      if (files.length === 0) {
          return res.status(400).send({
              message: 'File not found'
          });
      }

      res.writeHead(200, {'Content-Type': files[0].contentType});

      var i = 0;

      async.each(files, function (file, next) {

        file.position = i;

        var readstream = gfs.createReadStream({
            filename: file.filename
        });

        readstream.on('data', function (data) {
            res.write(data); 
        });

        readstream.on('error', function (err) {
            console.log('An error occurred!', err);
            throw err;
        });

        i++;

        next();

    }, function (err) {

        res.end();

    });

  });

});

Solution

  • You need to call next when readstream is done:

    readstream.on('end', function () {
      next();
    });