【发布时间】:2017-06-05 17:08:19
【问题描述】:
使用 node.js/Express.js,我想调用 API,将该调用的响应写入文件,然后将该文件作为附件提供给客户端。 API 调用返回正确的数据,并且该数据已成功写入文件;问题是当我尝试将该文件从磁盘流式传输到客户端时,提供的文件附件是空的。这是我的路由处理程序的主体:
// Make a request to an API, then pipe the response to a file. (This works)
request({
url: 'http://localhost:5000/execute_least_squares',
qs: query
}).pipe(fs.createWriteStream('./tmp/predictions/prediction_1.csv',
{defaultEncoding: 'utf8'}));
// Add some headers so the client know to serve file as attachment
res.writeHead(200, {
"Content-Type": "text/csv",
"Content-Disposition" : "attachment; filename=" +
"prediction_1.csv"
});
// read from that file and pipe it to the response (doesn't work)
fs.createReadStream('./tmp/predictions/prediction_1.csv').pipe(res);
问题:
为什么响应只是返回一个空白文档给客户端?
注意事项:
C1。发生此问题是因为当最后一行尝试读取文件时,写入过程尚未开始?
C1.a) createWriteStream 和 createReadStream 都是异步的事实是否不能确保在事件循环中 createWriteStream 将在 createReadStream 之前?
C2。会不会是“数据”事件没有被正确触发?不把这个抽象出来给你吗?
感谢您的意见。
【问题讨论】:
标签: javascript node.js express