Home >Web Front-end >Front-end Q&A >How to download files in nodejs
Node.js is an open source, cross-platform, JavaScript runtime that runs in a JavaScript runtime environment that can run JavaScript code on the server side. Node.js is widely used to develop high-performance, scalable web applications. Among them, file downloading is one of the basic functions of the website, and Node.js can also easily implement the file downloading function. This article will detail how to download files in Node.js.
1. Use the HTTP module to download files
In Node.js, you can use the HTTP module to download files. The HTTP module is one of the core modules of Node.js and provides APIs for creating HTTP clients and servers.
To download files, you need to perform the following basic steps:
(1) Create an HTTP request.
(2) Send HTTP request.
(3) Write the response to the file.
The following is the basic code:
const http = require('http'); const fs = require('fs'); const fileUrl = 'http://example.com/file.pdf'; const filePath = './file.pdf'; const request = http.get(fileUrl, (response) => { const fileStream = fs.createWriteStream(filePath); response.pipe(fileStream); }); request.on('error', (err) => { console.error(`请求下载文件出错: ${err.message}`); }); request.end();
In the above code, we first create an HTTP request through the get method of the HTTP module. In the request callback function, we create a writable file stream and write the response into the file stream through a pipe, thus writing the file to disk.
For large file downloads, it is very important to understand the download progress. We can use the built-in Content-Length
header to get the size of the file and the built-in progress
event to track the progress of the download. Here is an example:
const http = require('http'); const fs = require('fs'); const url = 'http://example.com/file.zip'; const filePath = './file.zip'; http.get(url, (response) => { const contentLength = parseInt(response.headers['content-length']); let downloadedLength = 0; response.pipe(fs.createWriteStream(filePath)); response.on('data', (chunk) => { downloadedLength += chunk.length; const percent = downloadedLength / contentLength * 100; console.log(`${percent}% downloaded`); }); response.on('end', () => { console.log('下载完成'); }); }).on('error', (err) => { console.error(`请求下载文件出错: ${err.message}`); });
In the above code, we use the built-in data
event to track the progress of the download and use the Content-Length
header to calculate Download percentage. When the download is complete, we output a "Download Completed" message.
Sometimes, file download links may be redirected. We can check if the status code of the response is 301 or 302 and use the Location
header to get the redirected link. Here is the sample code:
const http = require('http'); const https = require('https'); const fs = require('fs'); function downloadFile(url, filePath) { const httpClient = url.startsWith('https') ? https : http; httpClient.get(url, (response) => { const { statusCode } = response; if (statusCode === 301 || statusCode === 302) { console.warn(`文件重定向: ${response.headers.location}`); downloadFile(response.headers.location, filePath); return; } if (statusCode !== 200) { console.error(`请求下载文件出错: 状态码 ${statusCode}`); return; } response.pipe(fs.createWriteStream(filePath)).on('close', () => { console.log('下载完成'); }); }).on('error', (err) => { console.error(`请求下载文件出错: ${err.message}`); }); } const url = 'http://example.com/file.zip'; const filePath = './file.zip'; downloadFile(url, filePath);
In the above code, we use the httpClient
variable to check the protocol (http or https) and statusCode
to check the response status code. If it is 301 or 302, output the redirected message and re-download the file. If it is not 200, an error message is output.
2. Use the Request module to download files
In addition to the HTTP module, there are also some popular third-party modules in Node.js that can be used to download files, the most popular of which is Request module. The Request module is a simple, powerful, and user-friendly HTTP client created by Mikeal Rogers.
To use the Request module for file downloading, you first need to install it. You can execute the following command on the command line to install:
npm install request --save
The basic steps for downloading files using the Request module are similar to using the HTTP module. The following is a simple example:
const request = require('request'); const fs = require('fs'); const url = 'http://example.com/file.zip'; const filePath = './file.zip'; request(url) .pipe(fs.createWriteStream(filePath)) .on('finish', () => { console.log('下载完成'); }) .on('error', (err) => { console.error(`请求下载文件出错: ${err.message}`); });
In the above code, we use the request
method to create an HTTP request and write the response to a file stream through a pipe. When the download is complete, we output a "Download Completed" message.
To handle download progress, you can use the request object returned by the request
method. The size of the file can be obtained using the built-in Content-Length
header. In addition, the Request module provides a built-in progress
event that allows us to track the progress of the download. Here is an example:
const request = require('request'); const fs = require('fs'); const url = 'http://example.com/file.zip'; const filePath = './file.zip'; const fileStream = fs.createWriteStream(filePath); let downloadedLength = 0; request(url) .on('response', (response) => { const contentLength = parseInt(response.headers['content-length']); console.log(`文件大小: ${(contentLength / 1024 / 1024).toFixed(2)} MB`); response.on('data', (data) => { downloadedLength += data.length; const percent = downloadedLength / contentLength * 100; console.log(`${percent.toFixed(2)}% downloaded`); }); }) .pipe(fileStream) .on('finish', () => { console.log('下载完成'); }) .on('error', (err) => { console.error(`请求下载文件出错: ${err.message}`); });
In the above code, we use the response
event to get the size of the file and use the built-in data
event to calculate and output Download percentage.
Similar to the HTTP module, we can also use the Request module to handle file download link redirection. Here is an example:
const request = require('request'); const fs = require('fs'); const url = 'http://example.com/file.pdf'; const filePath = './file.pdf'; function downloadFile(url, filePath) { request(url) .on('response', (response) => { const { statusCode } = response; if (statusCode === 301 || statusCode === 302) { console.warn(`文件重定向: ${response.headers.location}`); downloadFile(response.headers.location, filePath); return; } if (statusCode !== 200) { console.error(`请求下载文件出错: 状态码 ${statusCode}`); return; } response.pipe(fs.createWriteStream(filePath)).on('finish', () => { console.log('下载完成'); }); }) .on('error', (err) => { console.error(`请求下载文件出错: ${err.message}`); }); } downloadFile(url, filePath);
In the above code, we use statusCode
to check the status code of the response. If it is 301 or 302, output the redirected message and re-download the file. If it is not 200, an error message is output.
Summary
This article introduces how to use the HTTP module and Request module to download files in Node.js. It includes the basic steps for downloading files using the HTTP module and Request module, handling download progress, and handling file download link redirection. Node.js provides a very convenient file download function, which can easily implement file download.
The above is the detailed content of How to download files in nodejs. For more information, please follow other related articles on the PHP Chinese website!