[英]Downloading file in typescript in Node.js
我正在嘗試使用 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();
})
});
但我收到以下錯誤:
Property 'pipe' does not exist on type 'Response'
我還檢查了節點獲取類型中的響應類型文件。 它沒有管道功能。
我在這里檢查了 node-fetch 的類型定義,根據這里的接口,響應體似乎是一個可讀流:
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;
}
並且有一個函數 pipeTo (我從這里的文檔中找到了這個。我在瀏覽了提到的文檔后嘗試運行以下代碼:
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();
})
});
但是我收到錯誤:
Argument of type 'WriteStream' is not assignable to parameter of type 'WritableStream<Uint8Array>'.
“WriteStream”類型缺少“WritableStream”類型中的以下屬性:locked、abort、getWriter
現在下面的代碼:
fs.createWriteStream(FILE_PATH, {encoding: "utf-8"});
返回一個實現了 stream.Writable 的 WriteStream 類型的對象( 在這里檢查)。 所以我不明白為什么 WriteStream 對象沒有提到的功能。
另外,我該如何解決這個問題? 是否有一種標准方法可以使用我無法弄清楚的 node.js 后端在打字稿中下載 http 文件? 或者我在這里遺漏了什么。
但我收到以下錯誤:
Property 'pipe' does not exist on type 'Response'
這個錯誤也是由這段代碼觸發的
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();
});
});
}
取自這里。 觸發錯誤是因為fetch
函數被解釋為 JS fetch 。
修復錯誤添加import nodeFetch from "node-fetch";
並將fetch(...)
替換為nodeFetch(...)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.