如何从createWriteStream中恢复错误并继续管道?

时间:2015-06-30 08:39:36

标签: node.js error-handling stream pipe

使用busboy处理node.js中的文件上传时

        var uploadStream = fs.createWriteStream(imagePath);


        uploadStream.on('error', function(err) {

            if (err.code === 'ENOENT') {
                // unknown dir
                mkdirp(imageDir, function(err) {
                    if (err) {
                        throw new Error('mkdirp error in upload')
                    } else {
                        // how to continue pipe from here?
                    }
                })
            }
        });

        file.on('data', function(data) {

            console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
        });
        file.on('end', function() {
            console.log('File [' + fieldname + '] Finished');
        });

        // save uploaded file
        file.pipe(uploadStream);

如果createWriteStream有一个未发现的目录,那么会触发一个错误事件,我试图通过创建该dir并继续上传管道来处理此错误,但我不知道如何继续上传我试过像

         uploadStream.on('error', function(err) {
            if (err.code === 'ENOENT') {
                // unknown dir
                mkdirp(imageDir, function(err) {
                    if (err) {
                        throw new Error('mkdirp error in upload')
                    } else {
                        file.pipe(uploadStream) // not work
                        file.pipe(fs.createWriteStream(imagePath)) // only get a part of uploaded image
                    }
                })
            }
            // uploadStream.end();
        });

请帮助!!!

0 个答案:

没有答案