How to download file node js

How to download file node js

How to download a file using NodeJS without any extra package

Posted on Jun 26, 2021

Download a file to your filesystem using NodeJS without any extra package

You can download a file (an image, a text, or any kind of file) and save it to your filesystem using NodeJS built-in https and fs module.

The https module allows you to create an HTTPS request using NodeJS, while the fs module grants you access to the filesystem.

By combining both modules, you can create an HTTPS GET request and write the response stream as a new file in your filesystem.

First, create a new file named download.js and import both modules to your script using the require() method as follows:

Then, create a url string to a file that can be accessed on the internet publicly.

Next, call the https.get() method and pass the url variable as its first argument. The second argument of the method will be the callback function you want to run once a response stream has been received:

Inside the callback function, write the name for the file you’re going to save as a path variable. For example, I want to save the image and name it as downloaded-image.png» :

Now you need to create a new writable stream using fs.createWriteStream() method and pass the path variable as its argument. The fs module will create the writable stream on the current folder by default:

Finally, send the GET response data stream to the writeStream object using the pipe() method. When the writeStream sends the finish signal, close the writeStream object:

The complete JavaScript code is as shown below:

You can execute the script using node command to see it in action:

You can get the command-line arguments from the process.argv property and stop the script when the user doesn’t pass both arguments to the script:

Pass the code above just below the imports as follows:

With that, you can reuse the download.js file to download a file from a URL. Each time you execute the script, pass the required url and path arguments from the command-line.

The example below will download the image from the first argument as save it as image.png :

And that’s how you can download a file using NodeJS without installing any extra package.

Bonus: download multiple files using NodeJS

Sometimes, you may need to download multiple files and save them into your system.

I’d recommend you use the npm download package instead of writing your own code.

The download package allows you to download multiple images and save them under a folder as shown below:

Level up your programming skills

I’m sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I’ll send new stuff straight into your inbox!

About

Nathan Sebhastian is a software engineer with a passion for writing tech tutorials.
Learn JavaScript and other web development technology concepts through easy-to-understand explanations written in plain English.

Node.js — How to Download a File

Moonshoot

Moonshoot is a
Student Feature.

You can download a file in Node.js in different ways. Node.js comes with built-in functions to download and save a file to your local disk. You can combine the integrated https and fs modules to download files from the Internet.

This tutorial shows you how to use native Node.js features to download a file from the Internet to your local computer.

Node.js Series Overview

Increase the Memory Limit for Your Process

Why You Should Add “node” in Your Travis Config

Create a PDF from HTML with Puppeteer and Handlebars

Create Your Own Custom Error

Retrieve a Request’s IP Address in Node.js

Detect the Node.js Version in a Running Process or App

How to Base64 Encode/Decode a Value in Node.js

Check if a Value Is Null or Undefined in JavaScript or Node.js

String Replace All Appearances

Remove All Whitespace From a String in JavaScript

Generate a Random ID or String in Node.js or JavaScript

Remove Extra Spaces From a String in JavaScript or Node.js

Remove Numbers From a String in JavaScript or Node.js

Get the Part Before a Character in a String in JavaScript or Node.js

Get the Part After a Character in a String in JavaScript or Node.js

How to Check if a Value is a String in JavaScript or Node.js

Check If a String Includes All Strings in JavaScript/Node.js/TypeScript

Check if a Value is a String in JavaScript and Node.js

Limit and Truncate a String to a Given Length in JavaScript and Node.js

Split a String into a List of Characters in JavaScript and Node.js

How to Generage a UUID in Node.js

Reverse a String in JavaScript or Node.js

Split a String into a List of Lines in JavaScript or Node.js

Split a String into a List of Words in JavaScript or Node.js

Detect if a String is in camelCase Format in Javascript or Node.js

Check If a String Is in Lowercase in JavaScript or Node.js

Check If a String is in Uppercase in JavaScript or Node.js

Get the Part After First Occurrence in a String in JavaScript or Node.js

Get the Part Before First Occurrence in a String in JavaScript or Node.js

Get the Part Before Last Occurrence in a String in JavaScript or Node.js

Get the Part After Last Occurrence in a String in JavaScript or Node.js

Filter Data in Streams

Get Number of Seconds Since Epoch in JavaScript

Get Tomorrow’s Date in JavaScript

Increase a Date in JavaScript by One Week

Add Seconds to a Date in Node.js and JavaScript

Add Month(s) to a Date in JavaScript or Node.js

Add Week(s) to a Date in JavaScript or Node.js

Get the Current Year in JavaScript or Node.js

How to Get a UNIX Timestamp in JavaScript or Node.js

How to Convert a UNIX Timestamp to a Date in JavaScript or Node.js

Add Days to a Date in JavaScript or Node.js

Get Yesterday’s Date in JavaScript or Node.js

How to Run an Asynchronous Function in Array.map()

How to Reset and Empty an Array

for…of vs. for…in Loops

Clone/Copy an Array in JavaScript and Node.js

Get an Array With Unique Values (Delete Duplicates)

Sort an Array of Integers in JavaScript and Node.js

Sort a Boolean Array in JavaScript, TypeScript, or Node.js

Check If an Array Contains a Given Value in JavaScript or Node.js

Add an Item to the Beginning of an Array in JavaScript or Node.js

Append an Item at the End of an Array in JavaScript or Node.js

How to Exit and Stop a for Loop in JavaScript and Node.js

Split an Array Into Smaller Array Chunks in JavaScript and Node.js

How to Get an Index in a for…of Loop in JavaScript and Node.js

How to Exit, Stop, or Break an Array#forEach Loop in JavaScript or Node.js

Retrieve a Random Item From an Array in JavaScript or Node.js

How to Reverse an Array in JavaScript and Node.js

Callback and Promise Support in your Node.js Modules

Run Async Functions/Promises in Sequence

Run Async Functions/Promises in Parallel

Run Async Functions in Batches

How to Fix “Promise resolver undefined is not a function” in Node.js or JavaScript

Detect if Value Is a Promise in Node.js and JavaScript

Overview of Promise-Based APIs in Node.js

Human-Readable JSON.stringify() With Spaces and Line Breaks

Write a JSON Object to a File

Create a Custom “toJSON” Function in Node.js and JavaScript

Securely Parse JSON

Check If a Value Is Iterable in JavaScript or Node.js

Extend Multiple Classes (Multi Inheritance)

Retrieve the Class Name at Runtime in JavaScript and Node.js

Generate a Random Number in Range With JavaScript/Node.js

Ensure a Positive Number in JavaScript or Node.js

How to Merge Objects

How to Check if an Object is Empty in JavaScript or Node.js

How to CamelCase Keys of an Object in JavaScript or Node.js

How to Snake_Case Keys of an Object in JavaScript or Node.js

How to Destructure a Dynamic Key in JavaScript or Node.js

How to Get All Keys (Including Symbols) from an Object in JavaScript or Node.js

How to Delete a Key From an Object in JavaScript or Node.js

Iterate Through an Object’s Keys and Values in JavaScript or Node.js

How to Convert URLSearchParams to Object

Get a File’s Created Date

Get a File’s Last Modified or Updated Date of a File

How to Create an Empty File

Check If a Path or File Exists

How to Rename a File

Check If a Path Is a Directory

Check If a Path Is a File

Retrieve the Path to the User’s Home Directory

How to Touch a File

Read File Content as String

Check If a Directory Is Empty

How to Create a Directory (and Parents If Needed)

Get a File‘s Extension

Get the Size of a File

Get a File Name (With or Without Extension)

Read a JSON File

Create From Object

Transform to an Object

Determine the Node.js Version Running Your Script

Check if a Value is a Symbol in JavaScript or Node.js

Detect if Running on Linux

Detect if Running on macOS

Detect if Running on Windows

Check if Running on 64bit or 32bit Platform

How to Download a File

Download a File in Node.js

Node.js’ https module allows you to send requests HTTPS requests. The given https.get method accepts the resource URL and an options object. In this example, we’re using the file URL on the Internet and skip the request options because we don’t need them.

The https.get method provides the response instance in a callback function. The response gives you access to the response status code, headers, and payload. Determine whether the request is successful and pipe the response data into a local file.

You can create a write stream piping the response data into a local target file. Here’s a sample function to download a file in Node.js:

Notice: the downloadFile function above wraps the https.get method into a promise. You may not need the promise. Modern Node.js code typically uses async/await instead of callbacks. That’s the reason you may want to use promises as well.

Then use the downloadFile method to download content from the Internet. For example, you may want to download a new wallpaper like this:

That’s it! Enjoy downloading files in Node.js!

Mentioned Resources

Get Notified on New Future Studio
Content and Platform Updates

Get your weekly push notification about new and trending
Future Studio content and recent platform enhancements

Table of Contents

Examples

Basic

Download a large file with default configuration

Get the progress of a download

If the response headers contain information about the file size, onProgress hook can be used. If the file size cannot be determined, «percentage» and «remainingSize» arguments will be called with NaN.

Get the deduced file name and override it

If you haven’t supplied a «fileName» config property, the program will try its best to choose the most appropriate name for the file(from the URL, headers, etc). In case you wish to know the name that was chosen, before the file is actually saved, use the onBeforeSave hook, which is called with the deduced name. If you’re «unhappy» with the name, it can be overridden by returning a new string. Returning anything else(including undefined/void), will let the program know that it can keep the name.

Custom file name

Normally, nodejs-file-downloader «deduces» the file name, from the URL or the response headers. If you want to choose a custom file name, supply a config.fileName property.

Overwrite existing files

By default, nodejs-file-downloader uses config.cloneFiles = true, which means that files with an existing name, will have a number appended to them.

If you want to completely skip downloading a file, when a file with the same name already exists, use config.skipExistingFileName = true

Send custom headers

Just add a «headers» property to the config object:

Hook into response

If you need to get the underlying response, in order to decide whether the download should continue, or perform any other operations, use the onReponse hook.

Repeat failed downloads automatically

The program can repeat any failed downloads automatically. Only if the provided config.maxAttempts number is exceeded, an Error is thrown.

Prevent unnecessary repetition

If you use the auto-repeat option, by setting the maxAttempts to greater than 1, «shouldStop» hook can be used, To decide whether the repetition should continue. This is useful in cases where you’re generating many dynamic url’s, some of which can result in a 404 http status code(for example), and there is no point in repeating that request.

Cancel a download

This feature is new. Kindly report any bugs you encounter. Useful for Electron apps.

Use a proxy

You can pass a proxy string. Under the hood, this will create a custom httpsAgent. This feature wasn’t tested extensively.

Error handling

downloader.download() will throw an error, just like Axios, in case of network problems or an http status code of 400 or higher.

If the auto-repeat feature is enabled(by setting the maxAttempts to higher than 1), then only a failure of the final attempt will throw an error.

Getting the response body during an error

If a status code of 400 or above is received, the program throws an error. In this case, a reference to the response body will be available in error.responseBody:

ECONNRESET

If you’re getting a consistent ECONNRESET error, it’s possible the server requires a User-Agent header to be sent. Try adding it:

Axios — Download Files & Images in Node.js

Moonshoot

Moonshoot is a
Student Feature.

Axios is a promise-based HTTP client for the browser and Node.js. It has a convenient and modern API simplifying asynchronous HTTP request and response handling. Let’s explore how to download files with Axios in Node.js.

Axios Series Overview

Download Files & Images in Node.js

Download Progress in Node.js

Axios File Download in Node.js

This tutorial is specifically for Node.js, because you’ll stream the image to a file on the disc. The streaming option isn’t supported in Axios when using the library in the browser. There you’d use the blob response type.

Select a File to Download

You need an accessible Internet URL linking to the resource to download a file. To illustrate the actual download implementation in Axios, let’s use the following “coding” picture from Markus Spiske which is publicly available on Unsplash.

You can access this image without restriction and even download it without registration.

How to download file node js. Смотреть фото How to download file node js. Смотреть картинку How to download file node js. Картинка про How to download file node js. Фото How to download file node js

The image example doesn’t mean you can’t download other file formats. It’s for illustration purposes and an image is visually appealing because you can look at it when opening the file on your hard disc.

Alright, you have a sample image and the related download URL. Let’s implement the actual download functionality.

Implement the Axios File Download in Node.js

The Axios initialization to request a file is equal to a request that expects another response payload format, like JSON. To download a file, explicitly define responseType: ‘stream’ as a request option. This tells Axios to provide the response.data as a readable stream.

From there, pipe the read-stream into a Node.js write-stream that points to a file on your local disc. This will pass the incoming bytes from your read-stream to the write-stream and ultimately flush every piece of the image to a local file.

Here’s a sample function to download an image:

This function defines a static URL and path to the local image file. You could pass both variables as function parameters to create a more general download method.

Initialize the Axios instance with the related HTTP method, URL and the mentioned stream value for the response type.

Wrapping the method’s response into a promise allows you to wait for the file to complete the download.

Because you’re using a stream as the response type, you want to wait for every byte of the incoming file. Do that by listening to the stream’s end event. This signals a successful data transmission. At this point, resolve the promise to complete the file transfer.

To recognize error situations, listen for the error event as well. The readable stream might signal the error event in situations like the underlying data flow interrupted. Handle this scenario as well.

Summary

Axios has great support for file downloads. If you’re an avid user of Axios, you can recognize that the response type differs from a regular json request.

Adjust the file download with Axios to your needs. We love to hear your thoughts and ideas. Tell us how you download files with Axios in the comments below or tweet us @futurestud_io.

Mentioned Resources

Get Notified on New Future Studio
Content and Platform Updates

Get your weekly push notification about new and trending
Future Studio content and recent platform enhancements

Node.js Download File to Client example with Express Rest API

In this tutorial, we’re gonna create Node.js Express example that provides Rest API to download file to Client from url (on server).

Node.js Express Download File overview

Our Node.js Application will provide APIs for:

This is the static folder that stores all files:

How to download file node js. Смотреть фото How to download file node js. Смотреть картинку How to download file node js. Картинка про How to download file node js. Фото How to download file node js

If we get list of files, the Node.js Rest Apis will return:

How to download file node js. Смотреть фото How to download file node js. Смотреть картинку How to download file node js. Картинка про How to download file node js. Фото How to download file node js

Each item in the response array has a url that you can use for downloading the file.

These are APIs to be exported:

MethodsUrlsActions
POST/uploadupload a File
GET/filesget List of Files (name & url)
GET/files/[filename]download a File

The source code at the end of this post will cover all of these APIs. But this tutorial only shows you how to get list of files’ info and download the file from server with url.

You can visit following tutorial for uploading files to the static folder:
Node.js Express File Upload Rest API example

Technology

Project Structure

This is the project directory that we’re gonna build:

How to download file node js. Смотреть фото How to download file node js. Смотреть картинку How to download file node js. Картинка про How to download file node js. Фото How to download file node js

– resources/static/assets/uploads : folder for storing files to download.
– file.controller.js exports functions to get files’ information and download a File with url.
– routes/index.js : defines routes for endpoints that is called from HTTP Client, use controller to handle requests.
– server.js : initializes routes, runs Express app.

Setup Node.js Express File Upload project

Open command prompt, change current directory to the root folder of our project.
Install Express, CORS modules with the following command:

The package.json file will look like this:

Create Controller for download File

controller/file.controller.js

Define Route for downloading file

When a client sends HTTP requests, we need to determine how the server will response by setting up the routes.

Create index.js file inside routes folder with content like this:

You can see that we use controller from file.controller.js.

Create Express app server

Finally, we create an Express server in server.js:

What we do are:
– import express and cors modules:

Run The App

How to download file node js. Смотреть фото How to download file node js. Смотреть картинку How to download file node js. Картинка про How to download file node js. Фото How to download file node js

– Retrieve list of Files’ information:

How to download file node js. Смотреть фото How to download file node js. Смотреть картинку How to download file node js. Картинка про How to download file node js. Фото How to download file node js

Conclusion

Today we’ve learned how to create Node.js Express Rest API to download file to Client with url from server static folder.

The source code at the end of this post will cover all of APIs including upload files.
Node.js Express File Upload Rest API example using Multer

Happy Learning! See you again.

Further Reading

You can also know way to upload an Excel file and store the content in MySQL database with the post:
Node.js: Upload/Import Excel file data into Database

Source Code

You can find the complete source code for this tutorial on Github.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *