如何使用 Node.js 下載檔案?
我們可以透過使用第三方庫或使用一些內建包在 Node.js 中下載檔案。
方法 1:使用“https”和“fs”模組
我們可以使用http GET 方法獲取要下載的檔案。
fs 模組中的createWriteStream() 方法建立一個可寫流並接收帶有檔案儲存位置引數的命令。
pipe() 是 fs 中的另一個方法,它從可讀流中讀取資料並將其寫入可寫流和檔案中。
示例 1
使用名稱downloadFile.js 建立一個檔案並複製以下程式碼段。建立檔案後,使用以下命令node downloadFile.js 執行此程式碼,如下例所示 −
const https = require("https"); const fs = require("fs"); // URL of the image const url = "https://tutorialspoint.tw/cg/images/cgbanner.jpg"; https.get(url, (res) => { const path = "downloaded-image.jpg"; const writeStream = fs.createWriteStream(path); res.pipe(writeStream); writeStream.on("finish", () => { writeStream.close(); console.log("Download Completed!"); }) })
輸出
C:\home
ode>> node downloadFile.js Download Completed!
方法 2:使用“download”庫
我們可以使用第三方“download”庫來安裝其依賴項並將其用於下載檔案。
安裝
npm install download
示例 2
// Download File using 3rd party library // Importing the download module const download = require('download'); // Path of the image to be downloaded const file = '/home/mayankaggarwal/mysql-test/tutorials_point_img.jpg'; // Path to store the downloaded file const filePath = `${__dirname}/files`; download(file,filePath) .then(() => { console.log('File downloaded successfully!'); })
輸出
C:\home
ode>> node downloadFile.js File downloaded successfully!
廣告