[英]Node (express.js) next() is called before end of stream
I have the following middleware function 我有以下中间件功能
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);
}
};
The files is being transfered correctly however sadly the next()
in the 该文件被正确地转移然而可悲的是
next()
的
req.on('end', function() {
writeStream.end();
next();
});
is called before it is done writing all data to the new file. 在将所有数据写入新文件之前调用。
My question is what am i doing wrong? 我的问题是我做错了什么? And how can i fix it?
我该如何解决?
Use the writable file stream's close
event to know when the file descriptor has been closed. 使用可写文件流的
close
事件可了解何时关闭文件描述符。
Replace this: 替换为:
var writeStream = fs.createWriteStream(req.filePath);
req.on('data', function(chunk) {
writeStream.write(chunk);
});
req.on('end', function() {
writeStream.end();
next();
});
with this: 有了这个:
req.pipe(fs.createWriteStream(req.filePath)).on('close', next);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.