Node.js   发布时间:2022-04-24  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了node.js – createWriteStream上的错误处理大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用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);

解决方法

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

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

当createWriteStream出现错误时,将调用错误处理程序并断开管道连接(unpiped),但传入的流(文件)在流中有未读数据且尚未使用.

通过调用.read(),它被读取(但没有传递给Writable流,因为没有人正在监听),并且结束事件被发送给读者.这触发了busboy.on(‘end’).

大佬总结

以上是大佬教程为你收集整理的node.js – createWriteStream上的错误处理全部内容,希望文章能够帮你解决node.js – createWriteStream上的错误处理所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。