[英]How to read a stream of data fetched on client side - JavaScript, Node JS
I have created a simple proxy using Node (Express), where I am reading a pdf file from a remote server.我使用 Node (Express) 创建了一个简单的代理,我正在从远程服务器读取 pdf 文件。 I am able to read the file in chunks, and sending the chunks in response as
res.write()
.我能够以块的形式读取文件,并以
res.write()
发送块作为响应。 When I log the data, I can see all the streaming, but I can't receive the chunks on the front end.当我记录数据时,我可以看到所有的流,但我无法在前端接收块。 I am calling the endpoints correctly, but I want to get a response for each chunk is read.
我正确地调用了端点,但我想为读取的每个块获得响应。
Client Side code客户端代码
fetch('http://localhost:8003/pdf-cors') .then(response => response.text()) .then(data => console.log(data));
Node Express code节点快递代码
app.get('/pdf-cors', (req, res) => { https.get('https://www.mazda.com/globalassets/en/assets/csr/download/2017/2017_all.pdf') .on('response', response => { response.on('data', data => { console.log("[Reading File]..."); res.write(data); }) response.on('end', _ => { console.log("File reading done !"); }) }) });
Note: When I put
res.end()
right afterres.write(data)
I am able to see the first chunk passed to the client in the console, but then I get an error saysError [ERR_STREAM_WRITE_AFTER_END]: write after the end
.注意:当我将
res.end()
放在res.end()
res.write(data)
我可以在控制台中看到传递给客户端的第一个块,但随后我收到一条错误消息Error [ERR_STREAM_WRITE_AFTER_END]: write after the end
.
The only thing that I want is to see each chunk being passed to the front end.我唯一想要的是看到每个块都被传递到前端。
Fetch API allows to stream data withReadableStream . Fetch API 允许使用ReadableStream流式传输数据。
On client side a stream can be read like:在客户端,流可以读作:
let res = await fetch('...');
let reader = res.body.getReader();
let result;
let decoder = new TextDecoder('utf8');
while (!result?.done) {
result = await reader.read();
let chunk = decoder.decode(result.value);
console.log(chunk);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.