简体   繁体   English

如何在NodeJS中处理未定义的上传

[英]How to handle undefined upload in NodeJS

I use BusBoy plugin to handle file upload. 我使用BusBoy插件来处理文件上传。 It registers a handler for event 'file' which is happening when the file has been uploaded completely,then the handler will do the next operation. 它为事件“文件”注册了一个处理程序,该事件在文件完全上传后发生,然后处理程序将进行下一个操作。 But when the upload file is undefined,event handler is registered but event 'file' never happens. 但是,当未定义上传文件时,将注册事件处理程序,但事件“文件”将永远不会发生。 It will take along time for process to stop handling this request. 处理将需要一段时间才能停止处理此请求。 When I keep on doing such thing for more than five times,the node process will halt for several minutes, it will come to normal after a few minutes. 当我继续这样做超过五次时,节点进程将停止几分钟,几分钟后它将恢复正常。

Then how can I handle this situation in NodeJS process? 那我该如何在NodeJS流程中处理这种情况呢? Don't tell me never to upload undefined, when file upload failed, I think such situation will also take place. 不要告诉我永远不要上传未定义的文件,当文件上传失败时,我认为这种情况也会发生。

you can use 'finish' event to stop processing 您可以使用“完成”事件来停止处理

busboy.on('finish', function() {
 //your code to stop processing
});

This 'finish' event will trigger when all files/fields events in the uploading (form) data have been triggered. 当上载(表单)数据中的所有文件/字段事件均已触发时,将触发此“完成”事件。 (Trigger is ignored if file/field is undefined). (如果未定义文件/字段,则忽略触发器)。

further it is recommended to recheck in your case to pipe your node request through busboy 进一步建议你的情况来复检, pipe你的节点request通过busboy

req.pipe(busboy);

I have solved this problem through this. 我已经通过这个解决了这个问题。 Set a variable flag for 'file' event, when the event happened the flag will be set true in its handler. 为“文件”事件设置一个变量标志,当事件发生时,该标志将在其处理程序中设置为true。 Because 'file' event happens before req.end event,so I register a handler for the end event of req. 由于“文件”事件在req.end事件之前发生,因此我为req的结束事件注册了一个处理程序。

req.on('end',function(){
    if(!flag){
         res.json({
            ....        
         });
    }

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM