Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/465.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在流结束之前调用节点(express.js)next()_Javascript_Node.js_Express_Fs - Fatal编程技术网

Javascript 在流结束之前调用节点(express.js)next()

Javascript 在流结束之前调用节点(express.js)next(),javascript,node.js,express,fs,Javascript,Node.js,Express,Fs,我有以下中间件功能 var bodyParser = require('body-parser'), fs = require('fs'); module.exports = function(req, res, next) { // Add paths to this array to allow binary uploads var pathsAllowingBinaryBody = [ '/api2/information/upload', '/api2/kpi

我有以下中间件功能

var bodyParser = require('body-parser'),
  fs = require('fs');
module.exports = function(req, res, next) {
  // Add paths to this array to allow binary uploads
  var pathsAllowingBinaryBody = [
    '/api2/information/upload',
    '/api2/kpi/upload',
  ];

  if (pathsAllowingBinaryBody.indexOf(req._parsedUrl.pathname) !== -1) {
    var date = new Date();
    req.filePath = "uploads/" + date.getTime() + "_" + date.getMilliseconds() + "_" + Math.floor(Math.random() * 1000000000) + "_" + parseInt(req.headers['content-length']);

    var writeStream = fs.createWriteStream(req.filePath);
    req.on('data', function(chunk) {
      writeStream.write(chunk);
    });
    req.on('end', function() {
      writeStream.end();
      next();
    });
  } else {
    bodyParser.json()(req, res, next);
  }
};
文件正在正确传输,但在

req.on('end', function() {
  writeStream.end();
  next();
});
在将所有数据写入新文件之前调用


我的问题是我做错了什么?如何修复它?

使用可写文件流的
close
事件了解文件描述符何时关闭

替换此项:

var writeStream = fs.createWriteStream(req.filePath);
req.on('data', function(chunk) {
    writeStream.write(chunk);
});
req.on('end', function() {
    writeStream.end();
    next();
});
为此:

req.pipe(fs.createWriteStream(req.filePath)).on('close', next);

真 的。那很容易!非常感谢你!我已经更新了我的答案,从技术上讲,它应该是
close
事件,这是来自
fs
模块的文件流使用的特殊事件。