首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法在Node中使用ndjson流,但类似的代码在React中工作。

无法在Node中使用ndjson流,但类似的代码在React中工作。
EN

Stack Overflow用户
提问于 2021-10-09 10:57:53
回答 1查看 705关注 0票数 3

我正在尝试使用来自lichess.org上的这个端点的数据。

下面是一个使用该数据流的React组件的最小工作示例。我正在使用一个名为坎-恩德森流的库。

代码语言:javascript
复制
import ndjsonStream from "can-ndjson-stream"
import { useEffect } from "react"

function App() {
  useEffect(() => {
    fetch("https://lichess.org/api/tv/feed")
      .then(res => ndjsonStream(res.body))
      .then(stream => {
        const streamReader = stream.getReader()
        streamReader.read().then(async res => {
          while (!res || !res.done) {
            res = await streamReader.read()
            console.log(res.value)
          }
        })
      })
      .catch(console.error)
  }, [])
  return <>Lorem Ipsum</>
}

export default App

但是,如果我试图编写相同的代码并在Node中运行它,如下所示:

代码语言:javascript
复制
import ndjsonStream from "can-ndjson-stream"
import fetch from "node-fetch"

fetch("https://lichess.org/api/tv/feed")
  .then(res => ndjsonStream(res.body))
  .then(stream => {
    const streamReader = stream.getReader()
    streamReader.read().then(async res => {
      while (!res || !res.done) {
        res = await streamReader.read()
        console.log(res.value)
      }
    })
  })
  .catch(console.error)

我知道这个错误:

ReferenceError: ReadableStream未在ndjsonStream中定义

因此,从fetch中提取的res似乎是空的或未定义的,但是获取其他API很好。

我还尝试使用axios而不是节点取,如下所示:

代码语言:javascript
复制
import ndjsonStream from "can-ndjson-stream"
import axios from "axios"

axios
  .get("https://lichess.org/api/tv/feed")
  .then(res => ndjsonStream(res.data))
  .then(stream => {
    const streamReader = stream.getReader()
    streamReader.read().then(async res => {
      while (!res || !res.done) {
        res = await streamReader.read()
        console.log(res.value)
      }
    })
  })
  .catch(console.error)

但它只是挂起,没有显示输出。感谢任何人,谁可以澄清这一点,或提供任何替代方式来运行这一节点。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-09 23:22:47

多亏了tromgy的评论,我才能做出一些有用的事情。我与库超任务一起帮助处理流的请求和管道。我还使用了尼德逊库。

以下是一些工作代码:

代码语言:javascript
复制
hyperquest("https://lichess.org/api/tv/feed")
    .pipe(ndjson.parse())
    .on("data", console.log)

注意,当对象带着on()的第二个参数到达时,您可以操纵它们,如下所示。

代码语言:javascript
复制
...
.on("data", (obj) => {
    foo(obj)
})
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69506089

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档