Node.js和请求模块:从可读stream开始上传

当用户上传我的node.js服务器上的文件时,我需要将相同的file upload到另一台服务器。

我想知道是否可以开始发送上传的部分到第二台服务器,而不必等待文件已经完整地上传到我的node.js服务器。

我正在使用请求模块https://github.com/mikeal/request上传到第二台服务器。

下面的代码等待,直到用户完成他的上传,然后再开始第二次上传(虽然我不是100%确定的):

app.post('/upload', function(req, res, next){ fs.readFile(req.files.file.path, function (err, data) { var newName = moment().format('YYYYMMDDHHmmss') + "_" + (Math.floor(Math.random() * (10000 - 0) + 0)); var name = newName + "." + req.files.file.extension; var newPath = "public/uploads/"+name; fs.writeFile(newPath, data, function (err) { if (err) { throw err; res.send("error"); } fs.unlink(req.files.file.path, function (err) { if (err) response.errors.push("Erorr : " + err); console.log('successfully deleted temp file : '+ req.files.file.path ); }); var uploadurl = "http://second.server.com/upload; var r = request.post(uploadurl, function optionalCallback (err, httpResponse, body) { if (err) { return console.error('upload failed:', err); } console.log('Upload successful! Server responded with:', body); }); var form = r.form(); form.append('file', fs.createReadStream(newPath)); res.send(newPath); }); }); }); 

这里是你如何使用busboy (注意:这要求你的当前bodyparsing中间件不会运行这个特定的路由,否则请求数据已经被占用):

 var Busboy = require('busboy'); // ... app.post('/upload', function(req, res, next) { var busboy = new Busboy({ headers: req.headers }), foundFile = false, uploadurl = 'http://second.server.com/upload', form, r; busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { if (foundFile || fieldname !== 'file') return file.resume(); // skip files we're not working with foundFile = true; r = request.post(uploadurl, function(err, httpResponse, body) { if (err) return console.error('upload failed:', err); console.log('Upload successful! Server responded with:', body); }); form = r.form(); form.append('file', file); }).on('finish', function() { res.send('File ' + (foundFile ? '' : 'not ') + 'transferred'); }); req.pipe(busboy); });