How to Efficiently Download Files Using Node.js
In Node.js, there are multiple ways to download files. However, if you don't require third-party libraries, you can rely on the built-in features or leverage the Fetch API.
Using the Fetch API (Node 18 or Later)
As of Node 18, the fetch global is available. It implements the Fetch API, enabling you to download data with built-in methods to work with the result as plain text, JSON, or binary data (as ArrayBuffer).
Leveraging HTTP Requests
For older versions of Node, you can create an HTTP GET request and pipe its response into a writable file stream using code similar to the example below:
const http = require('http'); // or 'https' for https:// URLs const fs = require('fs'); const file = fs.createWriteStream("file.jpg"); const request = http.get( "http://i3.ytimg.com/vi/J---aiyznGQ/mqdefault.jpg", function (response) { response.pipe(file); // Close the file stream after download is complete file.on("finish", () => { file.close(); console.log("Download Completed"); }); } );
Handling Command Line Arguments
If you need to gather information from the command line, consider using a tool like Commander.
Additional Resources
The above is the detailed content of How Can I Efficiently Download Files in Node.js?. For more information, please follow other related articles on the PHP Chinese website!