0
0
NodejsHow-ToBeginner · 3 min read

How to Download File in Node.js: Simple Guide with Examples

To download a file in Node.js, you can use the built-in https or http module to request the file and pipe the response to a writable stream like fs.createWriteStream. Alternatively, libraries like axios simplify this by handling the request and saving the file with less code.
📐

Syntax

Use the https.get() or http.get() method to request a file URL. Then pipe the response data to a writable file stream created by fs.createWriteStream(). This saves the file locally.

  • https.get(url, callback): Sends a GET request to the URL.
  • response.pipe(stream): Pipes the response data to the file stream.
  • fs.createWriteStream(path): Creates a writable stream to save the file.
javascript
const https = require('https');
const fs = require('fs');

https.get('file_url', (response) => {
  const fileStream = fs.createWriteStream('local_filename');
  response.pipe(fileStream);
  fileStream.on('finish', () => {
    fileStream.close();
    console.log('Download completed');
  });
});
💻

Example

This example downloads an image from a URL and saves it as image.jpg in the current folder. It shows how to handle the download stream and confirm when the file is saved.

javascript
const https = require('https');
const fs = require('fs');

const fileUrl = 'https://www.example.com/image.jpg';
const localPath = 'image.jpg';

https.get(fileUrl, (response) => {
  if (response.statusCode !== 200) {
    console.error(`Failed to get file: ${response.statusCode}`);
    response.resume(); // consume response data to free up memory
    return;
  }
  const fileStream = fs.createWriteStream(localPath);
  response.pipe(fileStream);

  fileStream.on('finish', () => {
    fileStream.close();
    console.log('Download completed successfully');
  });

}).on('error', (err) => {
  console.error(`Error: ${err.message}`);
});
Output
Download completed successfully
⚠️

Common Pitfalls

Common mistakes when downloading files in Node.js include:

  • Not handling HTTP errors or non-200 status codes, which can cause incomplete or failed downloads.
  • Not closing the file stream properly, leading to corrupted files.
  • Ignoring network errors, which can crash the program.
  • Using http module for https URLs or vice versa.

Always check the response status and handle errors gracefully.

javascript
const https = require('https');
const fs = require('fs');

// Wrong: ignoring status code and errors
https.get('https://example.com/file', (res) => {
  res.pipe(fs.createWriteStream('file'));
});

// Right: handle status and errors
https.get('https://example.com/file', (res) => {
  if (res.statusCode !== 200) {
    console.error('Download failed:', res.statusCode);
    res.resume(); // consume response to free memory
    return;
  }
  const fileStream = fs.createWriteStream('file');
  res.pipe(fileStream);
  fileStream.on('finish', () => fileStream.close());
}).on('error', (err) => {
  console.error('Request error:', err.message);
});
📊

Quick Reference

Tips for downloading files in Node.js:

  • Use https.get() for HTTPS URLs and http.get() for HTTP URLs.
  • Always check response.statusCode before saving.
  • Pipe the response to a writable stream from fs.createWriteStream().
  • Listen for finish event on the file stream to confirm completion.
  • Handle errors on both request and file streams.

Key Takeaways

Use built-in https or http modules with fs.createWriteStream to download files in Node.js.
Always check the HTTP response status code before saving the file.
Handle errors on both the request and file streams to avoid crashes.
Close the file stream after finishing to ensure the file is saved correctly.
Use the correct module (http or https) matching the file URL protocol.