0

尝试写入所有文件然后结束响应,但它以某种方式调用 res.end 在所有写入完成之前。我如何修复它,完成所有的写作,然后调用 res.end()?

错误消息 atm:错误:结束后写入

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

    });

  });

});
4

1 回答 1

1

您需要在完成next时调用readstream

readstream.on('end', function () {
  next();
});
于 2017-05-27T06:46:38.970 回答