How to Download Instagram Reels Using Node.js
In this, we will learn how to download Instagram Reels using Node.js in a simple and easy way. This project helps us understand Async/Await, handling JSON responses, and downloading files using streams.
Instagram does not provide a direct download option for Reels. So, we use a special npm library to fetch the direct video link and then save it to our computer.
This project is useful when :
- We want offline access to a public Reel
- We want to practice working with APIs
- We want to learn file handling in Node.js
Prerequisites:
Before we start, make sure you have the following installed:
- Node.js (Installed on your system)
- A Code Editor (VS Code recommended)
Step 1: Project Setup
First, we need to create a clean environment for our project. Open your terminal or command prompt and follow these steps :
1. Create a Project Folder
We create a dedicated folder to keep our project files organized.
mkdir insta-downloader cd insta-downloader
2. Initialize the Node Project
Next, we initialize a package.json file. This file acts as a manifest for our project, tracking our dependencies and script version. The -y flag skips the questionnaire and uses default settings.
npm init -y
3. Install Required Packages
We need two specific libraries to make this work:
- instagram-url-direct: To fetch the direct download link from Instagram.
- axios: To handle network requests and stream video downloads.
npm install instagram-url-direct axios
Step 2: Writing the Code
Create a new file named index.js in your project folder. We will write our script here.
1. Importing the Necessary Tools
At the top of the file, we import the necessary modules. We also use the built-in fs (File System) module to handle saving the file.
const { instagramGetUrl } = require("instagram-url-direct");
const axios = require("axios");
const fs = require("fs");- require (“instagram-url-direct”): We import the specific function instagramGetUrl from the library. This tool acts like a scraper-it takes a public Instagram link and finds the direct video URL that browsers use behind the scenes.
- require(“axios”): Axios is a popular HTTP client. We use it here to perform the actual download of the file from the internet.
- require(“fs”): This stands for File System. It is a built-in Node.js module that allows our code to write files (like creating the reel.mp4 file) on your computer’s hard drive.
2. The Async Function
async function downloadReel(url) { ... }We define a function named downloadReel. We mark it as async (asynchronous) because downloading files and talking to Instagram servers takes time. This keyword allows us to use await inside the function to pause and wait for data before moving to the next line.
3. Error Handling (Try-Catch)
try {
// ... code ...
} catch (error) {
console.error("An error occurred:", error);
}We wrap our code in a try……catch block. This is a safety net. If the internet connection fails or if the Instagram link is invalid (e.g., a private account), the program won’t crash. Instead, it catches the error and prints a helpful message to the console.
4. Fetching the Video Metadata
let links = await instagramGetUrl(url);
Here, we pass the Instagram post URL to our library. The code awaits the response. The result (links) is a JSON object that contains details about the post, including a list of direct video URLs.
5. Validating the URL
if (links.url_list && links.url_list.length > 0) {
const videoUrl = links.url_list[0];
// ...
}Before we try to download anything, we check if the library actually found a video. We ensure that url_list exists and is not empty. If it is valid, we grab the first URL (links.url_list[0]) to use for downloading.
6. Streaming the Download
const response = await axios({
url: videoUrl,
method: 'GET',
responseType: 'stream'
});We use Axios to request the video file.
- method: ‘GET’: We are asking to “get” data.
- responseType: ‘stram’: This is very important. Instead of downloading the whole video into your RAM (which could crash your app if the video is huge), we tell Axios to handle the data as a continuous flow (a stream).
7. Saving the File
const filePath = 'reel.mp4'; const writer = fs.createWriteStream(filePath); response.data.pipe(writer);
- fs. createWriteStream: This opens a new empty file named reel.mp4 on your computer, ready to accept data.
- .pipe(writer): This connects the download stream directly to the file stream.
Imagine a water pipe: data flows from the internet (Axios) through the pipe and directly into the file (writer) on your hard drive, chunk by chunk.
8. Handling Completion
writer.on('finish', () => {
console.log("Success! Video saved as reel.mp4");
});Since the download happens in the background, we attach an event listener .on(‘finish’). This waits for the stream to finish writing the file. Once it’s done, it runs the function inside to print “Success!” to the user.
9. Running the Script
const testURL = "https://www.instagram.com/reel/C-xyz123example/"; downloadReel(testURL);
Finally, we define a variable with a real Instagram URL and call our function to start the process.
Step 3: Complete Code
const { instagramGetUrl } = require("instagram-url-direct");
const axios = require("axios");
const fs = require("fs");
async function downloadReel(url) {
try {
console.log("Step 1: Fetching video metadata...");
// Fetch the direct video links
let links = await instagramGetUrl(url);
// Validate if we got a video URL
if (links.url_list && links.url_list.length > 0) {
const videoUrl = links.url_list[0];
console.log("Video URL found. Starting download...");
// Download the video using Axios Streams
const response = await axios({
url: videoUrl,
method: 'GET',
responseType: 'stream'
});
// Save the video to 'reel.mp4'
const filePath = 'reel.mp4';
const writer = fs.createWriteStream(filePath);
// Pipe the response data to the file
response.data.pipe(writer);
// Handle completion
writer.on('finish', () => {
console.log("Success! Video saved as reel.mp4");
});
// Handle errors during writing
writer.on('error', (err) => {
console.error("Error writing file:", err);
});
} else {
console.log("Error: No video found. The account might be private.");
}
} catch (error) {
console.error("An error occurred:", error);
}
}
// REPLACE THIS WITH A REAL INSTAGRAM REEL URL
const testURL = "https://www.instagram.com/reel/C-xyz123example/";
downloadReel(testURL);Step 4: Running the Project
- Find a public Instagram Reel Url (make sure the account is not private).
- Paste the URL into the testURL variable in your code.
- Run the script from your terminal.
node index.js
OutPut :
If everything is correct, you will see the following output in your terminal:
Step 1: Fetching video metadata... Video URL found. Starting download... Success! Video saved as reel.mp4
You can now open your project folder and watch the reel.mp4 file!
Leave a Reply