gpt4 book ai didi

node.js - createWriteStream 的错误处理

转载 作者:搜寻专家 更新时间:2023-10-31 22:45:57 25 4
gpt4 key购买 nike

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

最佳答案

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

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

createWriteStream 出错时,调用 error 处理程序并中断管道连接(unpiped),但传入流(file) 在流中有未读的数据并且还没有被消费。

通过调用 .read(),它被读取(但没有传送到 Writable 流,因为没有人在听)并且 end 事件被发送给读者。这会触发 busboy.on('end')

关于node.js - createWriteStream 的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20864036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com