NodeJS 将本机提取主体webstream转换为节点流时出现 typescript 错误

elcex8rz  于 2023-03-29  发布在  Node.js
关注(0)|答案(1)|浏览(96)

bounty将在3天后过期。回答此问题可获得+50声望奖励。danneu希望引起更多人关注此问题。
包.json

{
  "type": "module",
  "dependencies": {
    "@types/node": "^18.6.5",
    "typescript": "^4.7.4"
  }
}

系统配置json

{
  "compilerOptions": {
    "target": "ES2021",
    "module": "ESNext",
    "moduleResolution": "node",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}

使用node v18.7.0,我尝试将从本机获取API返回的webstream转换为节点流。我使用“node:stream”模块中的Readable.fromWeb方法。Typescript返回一个类型检查错误,但代码工作正常,带有@ts-ignore注解。

键入错误

Argument of type 'ReadableStream<Uint8Array>' is not assignable to parameter of type 'ReadableStream<any>'.
  Type 'ReadableStream<Uint8Array>' is missing the following properties from type 'ReadableStream<any>': values, [Symbol.asyncIterator]

const nodeStream = Readable.fromWeb(fetchRequest.body)

源代码

import { Readable } from 'node:stream'
import { pipeline } from 'stream/promises'
import fs from 'fs'

const fetchRequest = await fetch('https://www.npmjs.com/')

if (fetchRequest.body) {
  // Argument of type 'ReadableStream<Uint8Array>' is not assignable to parameter of type 'ReadableStream<any>'.
  // Type 'ReadableStream<Uint8Array>' is missing the following properties from type 'ReadableStream<any>': values, [Symbol.asyncIterator]
  // @ts-ignore
  const nodeStream = Readable.fromWeb(fetchRequest.body)

  await pipeline(nodeStream, fs.createWriteStream('output.html'))
}

export {}

是否有一个错误与获取打字或我做错了什么?
这里是一个生殖Playground

rfbsl7qr

rfbsl7qr1#

问题是你的fetch不是nodejs fetch,而是DOM fetch
@types/NodeJS没有fetch
https://github.com/DefinitelyTyped/DefinitelyTyped/issues/60924#issuecomment-1236920407
ThisIsNotTheFetchYouAreLookingFor.jpg
你可以用

import type * as streamWeb from 'node:stream/web';
declare global {
  interface Response {
    readonly body: streamWeb.ReadableStream<Uint8Array> | null;
  }
}

作为streamWeb.ReadableStream扩展ReadableStream
,或使用外部定义(如在链接线程中)

declare global {
    export const {
        fetch,
        FormData,
        Headers,
        Request,
        Response
    }: typeof import('undici')
    export type {FormData, Headers, Request, RequestInit, Response} from 'undici'
}

export {}

相关问题