如何使用 Node.js 下载文件?
可以使用内置包或第三方库来使用 node js 下载文件。
方法一:使用“https”和“fs”模块
GET 方法在 HTTPS 上用于获取要下载的文件。 createWriteStream() 是一种用于创建可写流的方法,它只接收一个参数,即要保存文件的位置。 pipe()是一种从可读流中读取数据并将其写入可写流的方法。
Javascript
const fs = require('fs');
const https = require('https');
// URL of the image
const url = 'GFG.jpeg';
https.get(url,(res) => {
// Image will be stored at this path
const path = `${__dirname}/files/img.jpeg`;
const filePath = fs.createWriteStream(path);
res.pipe(filePath);
filePath.on('finish',() => {
filePath.close();
console.log('Download Completed');
})
})
Javascript
const { DownloaderHelper } = require('node-downloader-helper');
// URL of the image
const file = 'GFG.jpeg';
// Path at which image will be downloaded
const filePath = `${__dirname}/files`;
const dl = new DownloaderHelper(file , filePath);
dl.on('end', () => console.log('Download Completed'))
dl.start();
Javascript
const download = require('download');
// Url of the image
const file = 'GFG.jpeg';
// Path at which image will get downloaded
const filePath = `${__dirname}/files`;
download(file,filePath)
.then(() => {
console.log('Download Completed');
})
- 'node-downloader-helper' 库
安装:
npm install node-helper-library
- 要下载的图像。
- 下载后必须保存图像的路径。
下面是从网站下载图像的代码。一个对象dl由类 DownloadHelper 创建,它接收两个参数:
file 变量包含将要下载的图像的 URL,而 filePath 变量包含将保存文件的路径。
Javascript
const { DownloaderHelper } = require('node-downloader-helper'); // URL of the image const file = 'GFG.jpeg'; // Path at which image will be downloaded const filePath = `${__dirname}/files`; const dl = new DownloaderHelper(file , filePath); dl.on('end', () => console.log('Download Completed')) dl.start();
- “下载”库
安装:
npm install download
下面是从网站下载图像的代码。下载函数接收文件和文件路径
Javascript
const download = require('download'); // Url of the image const file = 'GFG.jpeg'; // Path at which image will get downloaded const filePath = `${__dirname}/files`; download(file,filePath) .then(() => { console.log('Download Completed'); })
方法二:使用第三方库