首頁  >  文章  >  web前端  >  nodejs怎麼下載文件

nodejs怎麼下載文件

王林
王林原創
2023-05-27 20:43:051363瀏覽

在Node.js中,可以使用node-fetch和fs模組下載檔案。以下介紹如何使用這兩個模組下載檔案。

首先需要安裝node-fetch和fs模組。可以使用npm指令安裝:

npm install node-fetch fs

安裝完成後,就可以使用這兩個模組了。

下載檔案

下載檔案的過程可以分為幾個步驟:

  1. #傳送HTTP請求取得檔案資料
  2. 將資料寫入檔案

下面是一個下載檔案的範例程式碼:

const fetch = require('node-fetch');
const fs = require('fs');

const downloadFile = async (url, dest) => {
  const response = await fetch(url);

  if (!response.ok) {
    throw new Error(`failed to download file: ${response.statusText}`);
  }

  const fileStream = fs.createWriteStream(dest);
  await new Promise((resolve, reject) => {
    response.body.pipe(fileStream);
    response.body.on("error", (err) => {
      reject(err);
    });
    fileStream.on("finish", function() {
      resolve();
    });
  });
};

const fileUrl = 'https://example.com/files/file.txt';
const destPath = 'file.txt';

downloadFile(fileUrl, destPath)
  .then(() => {
    console.log('file downloaded successfully');
  })
  .catch((err) => {
    console.error('failed to download file:', err);
  });

這個程式碼首先使用node-fetch模組發送HTTP請求取得檔案數據,然後使用fs模組將資料寫入文件。要注意的是,在取得檔案資料的過程中,需要檢查HTTP回應狀態碼是否為200,如果不是,表示下載失敗。

程式碼中使用了async/await非同步語法和Promise物件來確保檔案資料寫入完成後再輸出結果。

更多選項

以上範例程式碼只是下載檔案的一個簡單範例,如果需要更多選項和功能,可以使用其他參數調整程式碼。

  1. 指定HTTP請求頭

可以使用node-fetch的headers參數來指定HTTP請求頭,例如:

const headers = {
  'Authorization': 'Bearer ' + token,
  'Content-Type': 'application/json'
};
const response = await fetch(url, {
  headers: headers
});
  1. 限制下載速度

如果需要限制下載速度,可以使用第三方模組speedline,例如:

const speedline = require('speedline');

const fileUrl = 'https://example.com/files/file.txt';
const destPath = 'file.txt';
const maxSpeed = 100; // 100 KB/s

const response = await fetch(fileUrl);
const stream = response.body;
const fileStream = fs.createWriteStream(destPath);
await speedline(stream.pipe(fileStream), maxSpeed);
  1. 快取下載檔案

如果需要緩存下載文件,可以使用第三方模組node-cache,例如:

const NodeCache = require('node-cache');
const fileCache = new NodeCache();

const downloadFile = async (url, dest) => {
  const cachedData = fileCache.get(url);
  if (cachedData) {
    return fs.writeFileSync(dest, cachedData);
  }
  
  const response = await fetch(url);

  if (!response.ok) {
    throw new Error(`failed to download file: ${response.statusText}`);
  }

  const fileData = await response.text();

  fileCache.set(url, fileData);
  fs.writeFileSync(dest, fileData);
};

以上是Node.js下載文件的基本知識和範例程式碼。根據實際需求和網路環境,可以選擇適合自己的參數和方法來下載檔案。

以上是nodejs怎麼下載文件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn