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

How Can I Download Files in Node.js Without Using External Libraries?

Linda Hamilton
Release: 2024-12-13 09:16:14
Original
779 people have browsed it

How Can I Download Files in Node.js Without Using External Libraries?

File Download in Node.js Without External Libraries

Downloading files in Node.js can be accomplished natively without relying on external libraries. Here's how:

Using the Built-in Fetch API (Node 18 )

Node 18 introduces the fetch global that implements the Fetch API. This API provides methods to download data, including text, JSON, and binary data. For example:

const fetch = require('node-fetch');

const url = 'http://example.com/file.jpg';
const response = await fetch(url);
const buffer = await response.arrayBuffer();

fs.writeFileSync('filename.jpg', Buffer.from(buffer));
Copy after login

Using HTTP GET Requests (Older Node Versions)

Prior to Node 18, you can create an HTTP GET request and pipe its response into a file stream:

const http = require('http');
const fs = require('fs');

const file = fs.createWriteStream('file.jpg');
const url = 'http://i3.ytimg.com/vi/J---aiyznGQ/mqdefault.jpg';
const request = http.get(url, (response) => {
  response.pipe(file);
});

// Close file stream after download completes
file.on('finish', () => {
  file.close();
  console.log('Download completed');
});
Copy after login

Configuring Command Line Options

If you require command-line options such as specifying a target file or URL, you can utilize a package like Commander for customization:

const program = require('commander');

program
  .option('-o, --output <file>', 'Output file name')
  .option('-u, --url <url>', 'URL to download from')
  .parse(process.argv);

const file = fs.createWriteStream(program.output || 'default.jpg');
const request = http.get(program.url, (response) => {
  response.pipe(file);
});
Copy after login

For more detailed information and alternative approaches, refer to the following resource: https://sebhastian.com/nodejs-download-file/

The above is the detailed content of How Can I Download Files in Node.js Without Using External Libraries?. For more information, please follow other related articles on the PHP Chinese website!

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