如何使用 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.com/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!
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP