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));
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'); });
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); });
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!