Using Axios to download images and videos in Node.js

Last updated on April 8, 2021 A Goodman Loading... Post a comment

Node.js is an asynchronous event-driven Javascript runtime that is designed to build scalable network applications. When handling files (from small images to large videos) with Node.js, you are free from the worries of dead-lock the process because there are no locks. This advantage comes from a reason is that almost no function in Node.js directly performs I/O.

In this article, we’ll cover how to download images and videos from the internet by using Node.js and a popular module named Axios.

Overview

Before jumping into the code, we will learn a little bit about Axios and some built-in methods of Node.js will be used to download files.

Axios

Axios is an easy-to-use and powerful HTTP request library and is often used with async / await.

Simple usage:

const axios = require("axios").default;

const downloadFile = async (url, path) => {
  try {
    const response = await axios({
      method: "GET",
      url: url,
      responseType: "stream",
    });
    // Do something with the response
  } catch (err) {
    // Handling errors
  }
};

fs.createWriteStream()

We’ll also use this method to quickly make a writable stream for the purpose of writing data to a file.

Syntax:

fs.createWriteStream( path, options )

Where:

  • path: (Required) This parameter holds the path of the file where to read the file. It can be String, Buffer, or URL
  • options: (Optional) it is an optional parameter that holds a string or object.

path.basename()

The path.basename() method is used to get the file name from the url, so we can save the file on our computer with the corresponding name.

Example Project

1. Navigate to the folder where you want to place your project then create a file name index.js and a folder named download (here’s where files will be saved to).

2. Install axios:

npm i axios

3. The code with detailed explanations

Add the following to your index.js file:

/* by Kindacode.com */
const fs = require('fs');
const path = require('path');
const axios = require('axios').default;

// fileUrl: the absolute url of the image or video you want to download
// downloadFolder: the path of the downloaded file on your machine
const downloadFile = async (fileUrl, downloadFolder) => {
  // Get the file name
  const fileName = path.basename(fileUrl);

  // The path of the downloaded file on our machine
  const localFilePath = path.resolve(__dirname, downloadFolder, fileName);
  try {
    const response = await axios({
      method: 'GET',
      url: fileUrl,
      responseType: 'stream',
    });

    const w = response.data.pipe(fs.createWriteStream(localFilePath));
    w.on('finish', () => {
      console.log('Successfully downloaded file!');
    });
  } catch (err) {
    throw new Error(err);
  }
}; 

// Testing
const IMAGE_URL =
  'https://www.kindacode.com/wp-content/uploads/2021/01/test.jpg';
downloadFile(IMAGE_URL, 'download');

const VIDEO_URL =
  'https://www.kindacode.com/wp-content/uploads/2021/01/example.mp4';
downloadFile(VIDEO_URL, 'download');

Now, execute your code and see what you have in the download folder and in your console logs. Here’s mine (I’m using Nodemon for development but it’s totally fine if you don’t have it):

Conclusion

In this article, we have walked through a complete example of downloading images and videos in Node.js. If you would like to learn more interesting stuff, see also the following articles:

You can also check out our Node.js topic page for the latest tutorials and examples.

Related Articles

guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x