在 Node.js 中下载 typescript 中的文件

Avn*_*esh 6 javascript node.js typescript

我正在尝试使用 node-fetch 下载带有 typescript (Node.js) 的文件。

根据此处的文档和堆栈溢出答案,以下代码应该有效:

public async downloadXMLFeed(): Promise<void>{
    // function for download the file to
    // a temporary location
    let fileStream = fs.createWriteStream(FILE_PATH, {encoding: "utf-8"});
    fetch(FILE_URL)
    .then((response) => {

        response.body.pipe(fileStream)

        fileStream.on("finish", () => {
            fileStream.close();
        })
    });
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

Property 'pipe' does not exist on type 'Response'
Run Code Online (Sandbox Code Playgroud)

我还检查了类型文件以获取节点获取类型的响应。它没有管道功能。

我在这里检查了节点获取的类型定义,根据此处的接口,响应的主体似乎是一个可读的流:

export class Body {
   constructor(body?: any, opts?: { size?: number; timeout?: number });
   arrayBuffer(): Promise<ArrayBuffer>;
   blob(): Promise<Buffer>;
   body: NodeJS.ReadableStream; // This should work.
   bodyUsed: boolean;
   buffer(): Promise<Buffer>;
   json(): Promise<any>;
   size: number;
   text(): Promise<string>;
   textConverted(): Promise<string>;
   timeout: number;
Run Code Online (Sandbox Code Playgroud)

}

并且有一个函数 pipelineTo (我从这里的文档中找到了这个。在浏览完上述文档后我尝试运行以下代码:

public async downloadXMLFeed(): Promise<void>{
    // function for download the file to
    // a temporary location
    let fileStream = fs.createWriteStream(FILE_PATH, {encoding: "utf-8"});
    fetch(FILE_URL)
    .then((response) => {

        response.body.pipe(fileStream)

        fileStream.on("finish", () => {
            fileStream.close();
        })
    });
Run Code Online (Sandbox Code Playgroud)

但是我收到错误:

Argument of type 'WriteStream' is not assignable to parameter of type 'WritableStream<Uint8Array>'.
Run Code Online (Sandbox Code Playgroud)

类型“WriteStream”缺少类型“WritableStream”中的以下属性:locked、abort、getWriter

现在有以下代码:

 fs.createWriteStream(FILE_PATH, {encoding: "utf-8"});
Run Code Online (Sandbox Code Playgroud)

返回一个 WriteStream 类型的对象(在此处检查),该对象实现了stream.Writable。所以我不明白为什么 WriteStream 对象没有提到的功能。

另外,我该如何解决这个问题?有没有一种标准方法可以使用我无法弄清楚的 Node.js 后端下载 TypeScript 中的 http 文件?或者我在这里遗漏了一些东西。

win*_*iz1 2

但我收到以下错误:

Property 'pipe' does not exist on type 'Response'
Run Code Online (Sandbox Code Playgroud)

此错误也是由此代码触发的

async function download() {
  const res = await fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png');
  await new Promise((resolve, reject) => {
    const fileStream = fs.createWriteStream('./octocat.png');
    res.body.pipe(fileStream);
    res!.body!.on("error", (err) => {
      reject(err);
    });
    fileStream.on("finish", function() {
      resolve();
    });
  });
}
Run Code Online (Sandbox Code Playgroud)

取自这里。该错误被触发是因为该fetch函数被解释为 JS fetch

要修复错误,请添加import nodeFetch from "node-fetch";并替换fetch(...)nodeFetch(...).