在createWriteStream上处理错误

我正在使用Node.js实现file upload,我的代码正常工作正常。

但是,当我写入文件失败(例如写入不存在的目录)时,它会调用error handling程序fstream.on('error', ...) ,但是它会卡住,永远不会继续。

我假定通过剪切inputstream,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); 

我通过在'error'事件处理程序中放置file.read()来解决这个问题。

 fstream.on('error', function(err) { console.log("ERROR:" + err); file.read(); }); 

createWriteStream出现错误时,调用error处理程序,并且pipe道连接被分解( unpiped ),但是传入stream( file )在stream中有未读数据并且没有被使用。

通过调用.read() ,它被读取(但是由于没有人正在监听,所以没有传递给Writablestream), end事件发送给读者。 这触发了busboy.on('end')