How to Run Python script via Node.js

Ahin Das
2 min readApr 18, 2023

By Ahin Subhra Das

Python is one of the world’s most popular, in-demand programming languages. But many people working with node.js in daily use and sometime they need support from python library for solution .That time what they will do ?

Here we take a tiny topic to archive airticle’s goal. The topic is we are going to make a youtube video downloader with node.js and python.

At first create a frontend view using angular, react,ejs template or any other to send youtube video link from frontend .We send data using request body in controller.js.


exports.getLink = async (req, res) => {
const youtubeLink=req.body.link;
}

In above code we write a function named getLink() within that declare a variable called youtubeLink.Now we need to send that link to our python script,for that we need to do install a npm package ‘child_process’.
In top of controller.js we require this package and from it we will take spawn function.

npm i child_process

const {spawn}=require(“child_process”);

After require spawn we will easyly sent our you tube link to python script,but remember you need to install python in your platform.
Below code is for calling python script where in spawn our platform’s python version,then as parameter we will send our python file name of my directory and youtubeLink which comes from frontend.


const resultSet = spawn(‘python3’, [‘downloader.py’,req.body.link]);

Now in python script we will get the link easily. Before that we need to install and require some python library like : sys & pytube. After getting the link we will print that link in terminal to check.

import sys
from pytube import YouTube
val = sys.argv[1]
print(val)

Then we use python pytube library [YouTube Module]to download youtube video in our directory. We can fetch the video title or select highest streaming resolution, lowest streaming resolution in which resolution we want to download the video in below code.

try:
print('try start')
# object creation using YouTube
# which was imported in the beginning
my_video = YouTube(val)
print(my_video.title)
d_video = my_video.streams.get_lowest_resolution()
# Lowest resolution video downloading
d_video.download()
print('success')
except:
print("Connection Error") #to handle exception

In this way we can download a video from youtube with node.js and python and the downloaded video will be saved in our project folder root directory.

pytube documentation : https://pytube.io/en/latest/

If you use type script for implementing node.js then you don’t need to call py script like this. You can simply call it from node.js api router to py script.

--

--