我正在使用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",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);