我有一个节点服务器(使用express)接受图像作为blob。我直接将其直接管理到外部请求,即:
app.post('/process', function(req, res) {
req.pipe({url: '<url-to-external-server>',...},
function(err,response,body) {
//process external response.
}
);
}
一切正常。现在我也想将数据保存到磁盘,所以我添加了这个功能,所以代码现在看起来像:
app.post('/process', function(req, res) {
var filename = generateUniqueFileName();
var writeStream = fs.createWriteStream(filename);
req.pipe(writeStream);
req.pipe({url: '<url-to-external-server>',...},
function(err,response,body) {
//process external response.
var respData = processBody(
if (!error && response.statusCode == 200) {
res.send(respData);
} else {
// send error.
res.send(...);
}
}
);
}
如果文件未正确保存,会发生什么。我在这里做错了什么?
答案 0 :(得分:2)
一条源流无法通过这种方式传送到2个目标流。您需要创建传递流(拆分源流)以管道到2个不同的目标。 Node的流模块有一个传递。以下是修改后的代码,其中包含传递:
app.post('/process', function(req, res) {
// create a pass through stream
var PassThrough = require('stream').PassThrough;
var passThroughStream = new PassThrough();
var filename = generateUniqueFileName();
var writeStream = fs.createWriteStream(filename);
req.pipe(passThroughStream); // split it to this new stream
passThroughStream.pipe(writeStream); // pipe this to 1st destination
// now pipe it to 2nd destination
req.pipe({url: '<url-to-external-server>',...},
function(err,response,body) {
//process external response.
var respData = processBody(
if (!error && response.statusCode == 200) {
res.send(respData);
} else {
// send error.
res.send(...);
}
}
);
}