如何读取客户端获取的数据流-JavaScript,Node JS
我已经使用Node(Express)创建了一个简单的代理,在这里我从远程服务器读取pdf文件。我能够以块的形式读取文件,并以如何读取客户端获取的数据流-JavaScript,Node JS,javascript,node.js,https,fetch,Javascript,Node.js,Https,Fetch,我已经使用Node(Express)创建了一个简单的代理,在这里我从远程服务器读取pdf文件。我能够以块的形式读取文件,并以res.write()的形式发送块作为响应。当我记录数据时,我可以看到所有的流,但我不能在前端接收数据块。我正确地调用了端点,但我想得到读取每个块的响应 客户端代码 fetch('http://localhost:8003/pdf-cors') .then(response=>response.text()) .then(data=>console.log(data))获
res.write()
的形式发送块作为响应。当我记录数据时,我可以看到所有的流,但我不能在前端接收数据块。我正确地调用了端点,但我想得到读取每个块的响应
客户端代码
fetch('http://localhost:8003/pdf-cors')
.then(response=>response.text())
.then(data=>console.log(data))代码>获取API允许使用流式传输数据
在客户端,流的读取方式如下:
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);
}
为什么不在response.on('end')
中调用res.end()。如果读取文件已结束(在末尾),则写入也已在同一点结束。您可以(可能应该)像这样使用pipe
:req.pipe(request.get(target)).pipe(res)代码>参见