在流结束之前调用节点(express.js)next() [英] Node (express.js) next() is called before end of stream
本文介绍了在流结束之前调用节点(express.js)next()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我具有以下中间件功能
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
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?
推荐答案
使用可写文件流的close
事件来了解何时关闭文件描述符.
Use the writable file stream's close
event to know when the file descriptor has been closed.
替换此:
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);
这篇关于在流结束之前调用节点(express.js)next()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文