如何读取客户端获取的数据流- JavaScript,Node JS

mfuanj7w  于 2023-08-04  发布在  Node.js
关注(0)|答案(2)|浏览(162)

我已经使用Node(Express)创建了一个简单的代理,在那里我从远程服务器上阅读一个pdf文件。我能够以块的形式读取文件,并以res.write()的形式发送块作为响应。当我记录数据时,我可以看到所有的流,但我不能在前端接收块。我正确地调用了端点,但我希望获得每个读取块的响应。

客户端代码

  1. fetch('http://localhost:8003/pdf-cors')
  2. .then(response => response.text())
  3. .then(data => console.log(data));

字符串

节点快速代码

  1. app.get('/pdf-cors', (req, res) => {
  2. https.get('https://www.mazda.com/globalassets/en/assets/csr/download/2017/2017_all.pdf')
  3. .on('response', response => {
  4. response.on('data', data => {
  5. console.log("[Reading File]...");
  6. res.write(data);
  7. })
  8. response.on('end', _ => {
  9. console.log("File reading done !");
  10. })
  11. })
  12. });


注意:当我把res.end()放在res.write(data)后面时,我可以在控制台中看到传递给客户端的第一个块,但随后我得到一个错误,显示Error [ERR_STREAM_WRITE_AFTER_END]: write after the end
我唯一想要的就是看到每个块都被传递到前端。

ukdjmx9f

ukdjmx9f1#

Fetch API允许使用ReadableStream流式传输数据。
在客户端,流可以读作:

  1. let res = await fetch('...');
  2. let reader = res.body.getReader();
  3. let result;
  4. let decoder = new TextDecoder('utf8');
  5. while (!result?.done) {
  6. result = await reader.read();
  7. let chunk = decoder.decode(result.value);
  8. console.log(chunk);
  9. }

字符串

fivyi3re

fivyi3re2#

如果您只需要服务器到客户端的事件,则可以将EventStream用于服务器发送的事件。

  1. export const apiEventSourceStream = async (onMessage) => {
  2. const url = `${API_IRL}/query-stream`;
  3. const eventSource = new EventSource(url);
  4. eventSource.onmessage = (event) => {
  5. onMessage(event.data);
  6. };
  7. eventSource.onerror = (error) => {
  8. console.error("EventSource error: ", error);
  9. eventSource.close();
  10. };
  11. return () => eventSource.close();
  12. };

字符串

展开查看全部

相关问题