我有以下中间件功能
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);
关于javascript - 在流结束之前调用 Node (express.js)next(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36312637/