我正在使用Node.js实现文件上传,并且我的代码在正常情况下可以正常工作。
但是,当我使它无法写入文件(例如,将其写入不存在的目录)时,它将调用错误处理程序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);
Run Code Online (Sandbox Code Playgroud)
我通过把解决问题file.read()的'error'事件处理程序。
fstream.on('error', function(err) {
console.log("ERROR:" + err);
file.read();
});
Run Code Online (Sandbox Code Playgroud)
出现createWriteStream错误时,error将调用处理程序并断开管道连接 ( unpiped),但传入流 ( file) 中有未读数据且尚未消耗。
通过调用.read(),它被读取(但没有传递到 Writable 流,因为没有人在听)并且end事件被发送给读取器。这触发busboy.on('end').
| 归档时间: |
|
| 查看次数: |
9659 次 |
| 最近记录: |