I run the sample code from node-fetch stream feature.
Sometime it can successfully parse the chunk, sometimes return error msg SyntaxError: Unexpected token { in JSON at position 312
const fetch = require('node-fetch');
async function main() {
const response = await fetch('https://httpbin.org/stream/3');
try {
for await (const chunk of response.body) {
console.log(JSON.parse(chunk.toString()));
}
} catch (err) {
console.error(err.stack);
}
}
main()
Anyone know why? Can I rely on the chunk?
By requesting
https://httpbin.org/stream/3, the server sends the data splitting into 3 chunks via stream. The client (in this case your node script) keeps connection with the server and keep receiving the data and splits them into chunks.The
node-fetchsimply splits data into chunks every time when a single asynchronous task is completed as you can see here: line 199 of body.js.So if the splitted data arrives so quickly that the asynchronous task receives multiple chunks of data within a single node's event loop,
node-fetchreceives multiple jason data.That's when the error occurs. Run the following code with
console.logadded. Then you can confirm that when error occurs, the multiple jason objects are kept in achunk.For this site, you can split the data by yourself when the error occurs as follows.
When you use Fetch API with a browser, you can actually write your own ReadableStreamReader and implement the strategy how to handle the splitted data.
Update:
You can simply use
stream-jsonlibrary's jsonl Parser as follows: