Non-Third-Party File Downloading in Node.js
For Node.js users seeking to download files without leveraging third-party libraries, several methods are available.
Using the Fetch API (Node 18 ):
Starting with Node 18, the built-in fetch API enables straightforward file downloading. The API offers several methods for working directly with the download result, including plaintext, JSON-converted data, and binary data.
Creating an HTTP GET Request:
For older Node versions, an HTTP GET request can be used. The response from this request is then piped into a writable file stream.
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); // After download completed close filestream file.on("finish", () => { file.close(); console.log("Download Completed"); }); });
Additional Features:
To enhance the command-line capabilities of your file downloading script, consider integrating a library like Commander. This tool allows you to specify target files, directories, and URLs.
For a more in-depth explanation of these methods, refer to the detailed guide at https://sebhastian.com/nodejs-download-file/.
The above is the detailed content of How Can I Download Files in Node.js Without Using Third-Party Libraries?. For more information, please follow other related articles on the PHP Chinese website!