繁体   English   中英

如何在Node.js中将文件附件流式传输到响应?

[英]How do I stream a file attachment to a response in node.js?

我想使用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。 可能是“数据”事件未正确触发吗? 难道不是为了您而将其抽象化吗?

感谢您的输入。

尝试这个 :

var writableStream = fs.createWriteStream('./tmp/predictions/prediction_1.csv',
{ defaultEncoding: 'utf8' })

request({
    url: 'http://localhost:5000/execute_least_squares',
     qs: query
}).pipe(writableStream);

//event that gets called when the writing is complete
writableStream.on('finish',() => {
    res.writeHead(200, {
    "Content-Type": "text/csv",
    "Content-Disposition" : "attachment; filename=" + 
    "prediction_1.csv"
});
    var readbleStream = fs.createReadStream('./tmp/predictions/prediction_1.csv')
   readableStream.pipe(res);
}

您应该捕获两个流(写和读)的on。('error'),以便可以返回合适的响应(否则为400)。

有关更多信息:

阅读Node.js Stream文档

注意事项:

发生此问题的原因是,到最后一行尝试读取文件时,写入文件的过程尚未开始吗?

答:可以。 或者另一种可能性是请求尚未完成。

createWriteStream和createReadStream都是异步的事实是否确保在事件循环中createWriteStream将在createReadStream之前?

答:从我在文档中所读的内容来看,createWriteStream和createReadStream是同步的,并且它们仅返回WriteStream / ReadStream对象。

可能是“数据”事件未正确触发吗? 难道不是为了您而将其抽象化吗?

答:如果您正在谈论此代码:

request({
    url: 'http://localhost:5000/execute_least_squares',
    qs: query
}).pipe(fs.createWriteStream('./tmp/predictions/prediction_1.csv', 
   {defaultEncoding: 'utf8'}));

它根据请求文档工作。 如果您在谈论其他问题,请更详细地说明。

暂无
暂无

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

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