Home > Web Front-end > JS Tutorial > How Can I Download Files in Node.js Without Using Third-Party Libraries?

How Can I Download Files in Node.js Without Using Third-Party Libraries?

Mary-Kate Olsen
Release: 2024-12-03 07:09:09
Original
332 people have browsed it

How Can I Download Files in Node.js Without Using Third-Party Libraries?

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");
   });
});
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template