我正在使用以下代码连接到 SSE 流:
const getNonTradingEventsUsingHttp = async (onData: (data: string) => void): Promise<any | void> => {
return new Promise((resolve, reject) => {
https.get(new URL(`https://some.com/events`), { headers: { Authorization: this.authHeader(apiKey, apiSecret) } }, res => {
res.on('data', data => processSSEDataframe(data.toString()).forEach(onData))
res.on('end', resolve)
res.on('error', (err: any) => reject(err))
})
})
}
processSSEDataframe = (dataframe: string): string[] => {
/**
* Takes in a raw dataframe from a Server Sent Events stream,
* parses the message and returns an array of string objects
* representing JSON data that can be used upstream.
*
* We return an array because the dataframe can include no
* data objects (e.g. the welcome message), or it cane include
* multiple objects (separated by \n\n)
*/
const messages = dataframe.split('\n\n')
const data: string[] = []
messages.forEach(msg => {
if (msg.startsWith(': welcome')) {
console.log('Connected to events stream')
return // skip
}
const dataFramePrefix = 'data:'
if (msg.startsWith(dataFramePrefix)) {
const contents = msg.slice(dataFramePrefix.length).trim()
data.push(contents)
return // done
}
})
return data
}
现在,使用它是小菜一碟。我只是这样称呼它:
const onData = (data: string) => {
console.log(JSON.parse(data))
}
await getNonTradingEventsUsingHttp(onData);
问题
当我运行脚本时,我得到一个 JSON 解析器错误:
SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
当我检查data
字符串时,我发现它已被截断:
{...,"net_amount":31467.62,"per_share_amount":n // <-- the rest is missing!
我试过在 CURL 中运行这个命令,我没有这个问题。
我还添加了调试断点res.on('end')
并res.on('error')
查看它们是否导致流突然结束,但都没有被触发。
你能帮我弄清楚为什么我的 Node 程序中的输出会被截断吗?