我正在使用Node.js实现文件上传,我的代码在正常情况下工作正常. 但是,当我使它无法写入文件(例如,将其写入不存在的目录)时,它会调用错误处理程序,fstream.on(‘error’,…),但它会卡住并
但是,当我使它无法写入文件(例如,将其写入不存在的目录)时,它会调用错误处理程序,fstream.on(‘error’,…),但它会卡住并且永远不会继续.
我假设通过删除传入的流,busboy继续进行下一部分处理,但似乎并非如此.
我想运行相同的busboy.on(‘end’)来响应浏览器(带有一些错误信息),但是如何才能调用它?
var express = require("express");
var Busboy = require('busboy');
var fs = require('fs');
var upload = require('./upload');
var Path = require('path');
var app = express();
app.get("/", function(request, response) {
response.writeHead(200, { Connection: 'close'});
response.end('<html><body>' +
'<form action="/upload" method="post" enctype="multipart/form-data">' +
' <input type="file" name="filefield">' +
' <input type="submit">' +
'</body></html>');
});
app.post("/upload", function(request, response) {
// request.files will contain the uploaded file(s),
// keyed by the input name (in this case, "file")
console.log(request.body);
var fileId = upload.generateId();
var busboy = new Busboy({headers: request.headers});
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
var path = Path.join('images', fileId);
console.log('hello');
var fstream = fs.createWriteStream(path);
fstream.on('end', function() {
console.log("EOF");
});
fstream.on('close', function() {
console.log("CLOSE");
});
fstream.on('error', function(err) {
console.log("ERROR:" + err);
file.unpipe();
fstream.end();
});
fstream.on('finish', function() {
console.log('onFinish');
})
file.on('end', function() {
console.log('file end');
});
file.pipe(fstream);
});
busboy.on('end', function() {
console.log('busboy end');
response.json({id:fileId});
});
request.pipe(busboy);
});
app.listen(3000);
我通过将file.read()放在’error’事件处理程序中解决了这个问题.
fstream.on('error', function(err) {
console.log("ERROR:" + err);
file.read();
});
当createWriteStream出现错误时,将调用错误处理程序并断开管道连接(unpiped),但传入的流(文件)在流中有未读数据且尚未使用.
通过调用.read(),它被读取(但没有传递给Writable流,因为没有人正在监听),并且结束事件被发送给读者.这触发了busboy.on(‘end’).
