【问题标题】:Node res.write all data before res.end() is called节点 res.write 调用 res.end() 之前的所有数据
【发布时间】:2017-10-28 01:29:10
【问题描述】:

尝试写入所有文件然后结束响应,但它以某种方式在所有写入完成之前调用 res.end。 我该如何解决它,完成所有的写作,然后调用 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();

    });

  });

});

【问题讨论】:

    标签: node.js express async.js gridfs-stream


    【解决方案1】:

    readstream 完成后,您需要调用 next

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-03
      • 1970-01-01
      • 2017-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多