Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How to Download a File using Express.js ?
Next article icon

How to Download a File Using Node.js?

Last Updated : 08 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Downloading files from the internet is a common task in many Node.js applications, whether it’s fetching images, videos, documents, or any other type of file. In this article, we’ll explore various methods for downloading files using Node.js, ranging from built-in modules to external libraries.

Using Built-in Modules

Table of Content

  • Using the http or https Module
  • Using third party libraries
  • Using download Library

Using the http or https Module

Node.js has built-in modules like ‘https’ and ‘http’ for making HTTP requests. You can utilize these modules to download files from a remote server. The GET method is used on HTTPS to retrieve the file to be downloaded. The ‘createWriteStream()’ method is used to create a writable stream and takes only one argument, which is the location where the file is to be saved. Additionally, the ‘pipe()’ method reads the data from the readable stream and writes it to the writable stream.

Example: Implementation to show how to download files using an HTTP module.

Node
const http = require('http'); const fs = require('fs');  const fileUrl = 'http://example.com/file.txt'; const destination = 'downloaded_file.txt';  const file = fs.createWriteStream(destination);  http.get(fileUrl, (response) => {     response.pipe(file);     file.on('finish', () => {         file.close(() => {             console.log('File downloaded successfully');         });     }); }).on('error', (err) => {     fs.unlink(destination, () => {         console.error('Error downloading file:', err);     }); }); 

Step to Run Application: Run the application using the following command from the root directory of the project

node .\app.js
Screenshot-2024-06-07-165929

Using third party libraries

The node-downloader-helper library provides a convenient and feature-rich solution for downloading files in Node.js applications. It simplifies the process of downloading files from the internet by handling tasks such as progress tracking, resuming interrupted downloads, and error handling. In this article, we’ll explore how to use the node-downloader-helper library to download files in Node.js.

Installation: 

npm install node-helper-library

The file variable contains the URL of the image which will be downloaded and filePath variables contain the path where the file will be saved.

Example: Implementation to show how to download files using third party libraries.

Node

</p><pre><code class="language-node"></code></pre><p></p><pre></pre><p><br></p><pre><code><span>const { DownloaderHelper } = require('node-downloader-helper');</span></code><br><br><code><span>// URL of the image</span></code><br><code><span>const file = 'GFG.jpeg';</span></code><br><code><span>// Path at which image will be downloaded</span></code><br><code><span>const filePath = `${__dirname}/files`; </span></code><br><br><code><span>const dl = new DownloaderHelper(file , filePath);</span></code><br><br><code><span>dl.on('end', () => console.log('Download Completed'))</span></code><br><code><span>dl.start();</span></code><br></pre><p dir="ltr"><br></p><p dir="ltr"><b><strong>Step to Run Application:</strong></b><span> Run the application using the following command from the root directory of the project</span></p><pre><span>node .\app.js</span></pre>[caption width="800"]<img src="https://media.geeksforgeeks.org/wp-content/uploads/20240607170621/Screenshot-2024-06-07-165929.png" alt="Screenshot-2024-06-07-165929" width="601" height="157" srcset="https://media.geeksforgeeks.org/wp-content/uploads/20240607170621/Screenshot-2024-06-07-165929.png 601w,https://media.geeksforgeeks.org/wp-content/uploads/20240607170621/Screenshot-2024-06-07-165929-100.png 100w,https://media.geeksforgeeks.org/wp-content/uploads/20240607170621/Screenshot-2024-06-07-165929-200.png 200w,https://media.geeksforgeeks.org/wp-content/uploads/20240607170621/Screenshot-2024-06-07-165929-300.png 300w" loading="lazy"> [/caption]<p dir="ltr"><br></p><p dir="ltr"><span>Below is the code for downloading an image from a website. An object </span><b><strong>dl </strong></b><span>is created of class DownloadHelper which receives two arguments: The image which is to be downloaded. The path where the image has to be saved after downloading.</span></p><h2 id="using-download-library"><b><strong>Using download Library</strong></b></h2><p dir="ltr"><span>The </span><code><span>download</span></code><span> library simplifies the process of downloading files in Node.js applications by providing a straightforward API for making HTTP requests and saving the downloaded files to the local file system. In this article, we'll explore how to use the </span><code><span>download</span></code><span> library to download files in Node.js.</span></p><h3 id="installation-1"><span>Installation:</span></h3><pre><span>npm install download</span></pre><p dir="ltr"><b><strong>Example:</strong></b><span> Implementation to show how to download files using </span><b><strong>download</strong></b><span> libraries.</span></p><p dir="ltr"><gfg-tabs data-run-ide="false" data-mode="light"><gfg-tab slot="tab">Node 

 


const download = require('download');

// Url of the image
const file = 'GFG.jpeg';
// Path at which image will get downloaded
const filePath = `${__dirname}/files`;

download(file,filePath)
.then(() => {
console.log('Download Completed');
})


Step to Run Application: Run the application using the following command from the root directory of the project

node .\app.js

console output of all the above three codes




Next Article
How to Download a File using Express.js ?

P

pritishnagpal
Improve
Article Tags :
  • Node.js
  • Technical Scripter
  • Web Technologies
  • NodeJS-Questions
  • Technical Scripter 2020

Similar Reads

  • How to Download a File using Express.js ?
    Express.js is a routing and middleware framework for handling the different routing of the webpage and it works between the request and response cycle and works on the top of the node.js server. In this article, we will discuss how to download a file using express.js. ApproachTo download a file usin
    3 min read
  • How to download File Using JavaScript/jQuery ?
    The ability to download files directly from a website is an essential feature for many web applications. Whether you're providing documents, images, or other data, enabling users to download files seamlessly enhances their experience and ensures they can access the content offline. This article prov
    2 min read
  • How to Add Data in JSON File using Node.js ?
    JSON stands for Javascript Object Notation. It is one of the easiest ways to exchange information between applications and is generally used by websites/APIs to communicate. For getting started with Node.js, refer this article. Prerequisites:NPM NodeApproachTo add data in JSON file using the node js
    4 min read
  • How to truncate a file using Node.js ?
    In this article, we are going to explore How to truncate the complete file using Node. There are two methods to truncate the file of all its data. We can either use the fs.truncate() method or the fs.writeFile() method to replace all the file content. Method 1: The fs.truncate() method in Node.js ca
    3 min read
  • How to read and write JSON file using Node ?
    Node JS is a free and versatile runtime environment that allows the execution of JavaScript code outside of web browsers. It finds extensive usage in creating APIs and microservices, catering to the needs of both small startups and large enterprises. JSON(JavaScript Object Notation) is a simple and
    3 min read
  • How to convert a file to zip file and download it using Node.js ?
    The Zip files are a common way of storing compressed files and folders. In this article, I'll demonstrate how to convert the file to zip format by using the adm-zip module (NPM PACKAGE). Uses of ADM-ZIP compress the original file and change them to zip format.update/delete the existing files(.zip fo
    3 min read
  • How to Implement File Download in NextJS using an API Route ?
    In web development, facilitating file downloads is a common requirement, whether it's providing users with documents, images, or other media files. NextJS, with its versatile API routes and server-side capabilities, offers an elegant solution for implementing file downloads. In this article, we'll e
    5 min read
  • How to Copy a File in Node.js?
    Node.js, with its robust file system (fs) module, offers several methods to copy files. Whether you're building a command-line tool, a web server, or a desktop application, understanding how to copy files is essential. This article will explore various ways to copy a file in Node.js, catering to bot
    2 min read
  • How to Download PDF File on Button Click using JavaScript ?
    Sometimes, a web page may contain PDF files that can be downloaded by the users for further use. Allowing users to download the PDF files can be accomplished using JavaScript. The below methods can be used to accomplish this task. Table of Content Using html2pdf.js libraryUsing pdfmake LibraryUsing
    5 min read
  • How To Read a File Line By Line Using Node.js?
    To read a file line by line in Node.js, there are several approaches that efficiently handle large files and minimize memory usage. In this article, we'll explore two popular approaches: using the Readline module (which is built into Node.js) and using the Line-reader module, a third-party package.
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences