Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Node.js

    Node.js Lesson 11: Echo Server

    Git

    Getting started with Git Hooks using ghooks

    React

    Build Real-World React Native App #8 : implement Dark mode

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Wednesday, September 10
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / JavaScript / Node.js / Building a Simple CLI Youtube Video Downloader in NodeJS
    JavaScript

    Building a Simple CLI Youtube Video Downloader in NodeJS

    bradstarartBy bradstarartMarch 4, 2020No Comments7 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Building a Simple CLI Youtube Video Downloader in NodeJS
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link
    Building a Simple CLI Youtube Video Downloader in NodeJS
    Building a Simple CLI Youtube Video Downloader in NodeJS

    Command Line Interfaces (CLIs) have been around for close to 50 years now, and still seem to be going strong. Even in the age of amazing libraries like React, VueJS, and Angular, text-based terminals remain the best way to accomplish a multitude of tasks.

    CLIs are incredibly useful for developers seeking to automate workloads, e.g. when deploying new applications, running tests and migrating data. Besides, a lot of times, building a Graphical User Interface (GUI) is complete overkill for something that could be easily accomplished with just a few lines of code.

    NodeJS is the perfect language for writing CLI apps thanks to the multitude of built-in libraries available for everything from network communication to reading and writing files. If you’re feeling lazy like every developer does every once in a while, the million of packages available on registries like NPM and YARN will definitely come in handy.

    In this tutorial, we create a basic NodeJS CLI app for downloading music files from Youtube and converting them to MP3. This will serve as an introduction on how to interact with web interfaces through the CLI, style the output and accept arguments through the command line.

    Setting Up the Project

    First things first, we’ll set up our project by initializing NPM (which creates a ‘package.json’ file for us) and ‘git’ (because every project needs git).

    Assuming you already created a project folder, simply run

    npm init && git init

    Then let’s get all the dependencies out of the way. Each of them will be covered in more specific detail later on in this guide.

    npm install commander ora youtube-mp3-downloader -S
    • Commander is a library that takes care of a lot of CLI boilerplate. It’s incredibly useful when you just want to get a project running in the shortest time possible.
    • Ora adds styling to our command line output
    • Youtube-mp3-downloader does what the package name suggests – it pulls videos from Youtube and converts them to mp3 files.

    Downloading Files from Youtube

    First, let’s create a ‘downloader.js’ file in ‘src/downloader.js.’ This will be responsible for handling downloads and storage locations.

    It takes the following options:

    • ffmpegPath: ffmpeg installation location. ffmpeg is a large open-source program used for handling audio and video files. In our case, it’s responsible for converting video files to mp3 format. If you don’t have it installed, run sudo apt install ffmpeg To check the installation location on your system, run which ffmpeg
    • outputPath: where music files will be saved
    • youtubeVideoQuality: download quality. “highest”, “lowest” or a number from 1-10
    • queueParallelism: how many files can be converted consecutively
    • progressTimeout: how often the progress indicator should be updated
    const YoutubeMp3Downloader = require('youtube-mp3-downloader');
    const downloader = new YoutubeMp3Downloader({
       ffmpegPath: "/usr/bin/ffmpeg",
       outputPath: "/home/cray/mp3-downloads",
       youtubeVideoQuality: 'highest',
       queueParallelism: 3,
       progressTimeout: 5000
    });
    

    The ‘downloader’ instance accepts two arguments – the Youtube video id and the name of the file once downloaded. The second argument is optional.

    Read More:  All You Should Know About Web Development in 2020 [Trends]

    Let’s export a function that will make the downloader option accessible to other files.

    let url = require('url');
    module.exports = {
       download: function (videoIdOrLink, fileName) {
           return new Promise(((resolve, reject) => {
               if (!videoIdOrLink) {
                   throw new Error("Please enter a valid video id or link")
               }
               let videoId = videoIdOrLink;
               if (isURL(videoIdOrLink)) {
                   let urlQueryObj = url.parse(videoIdOrLink, true).query
                   videoId = urlQueryObj.v;
               }
               downloader.download(videoId, fileName);
               downloader.on('finished', function (err, data) {
                   resolve(data);
               });
               downloader.on('error', function (err) {
                   reject(err);
               });
           }))
       },
       downloader
    };
    

    First, copy-pasting the video id from every link we want to download is a little cumbersome. Instead, we check if whatever has been input by the user is a URL, and if so, extract the ‘v’ query from the Youtube URL.

    Recall that Youtube URLs typically look like this: https://www.youtube.com/watch?v=4l1gNOocZu8. The id is the 4l1gNOocZu8 part.

    The isURL helper is borrowed from Stackoverflow and looks like this:

    module.exports.isURL = function (str) {
       const urlRegex = '^(?!mailto:)(?:(?:http|https|ftp)://)(?:S+(?::S*)?@)?(?:(?:(?:[1-9]d?|1dd|2[01]d|22[0-3])(?:.(?:1?d{1,2}|2[0-4]d|25[0-5])){2}(?:.(?:[0-9]d?|1dd|2[0-4]d|25[0-4]))|(?:(?:[a-zu00a1-uffff0-9]+-?)*[a-zu00a1-uffff0-9]+)(?:.(?:[a-zu00a1-uffff0-9]+-?)*[a-zu00a1-uffff0-9]+)*(?:.(?:[a-zu00a1-uffff]{2,})))|localhost)(?::d{2,5})?(?:(/|?|#)[^s]*)?$';
       const url = new RegExp(urlRegex, 'i');
       return str.length < 2083 && url.test(str);
    };
    

    url.parse is taken from the built-in NodeJS library and accepts two parameters – the url and a boolean indicating whether it should parse for query strings (which we want in this case). It then returns an object with all the queries.

    Finally, we call the download function with the now-extracted video id.

    Now comes the fun part.

    Interacting With a NodeJS App Through the Command Line

    While it’s entirely possible to write a NodeJS CLI app with Vanilla Javascript, Commander makes it much easier to do so.

    const program = require("commander");
    
    program.version('0.0.1').description("A simple node-cli youtube downloader");
    
    program.command('ytd')
       .requiredOption('-l, --link <link>', 'A youtube video link or id')
       .option('-n, --name [name]', 'Name of the downloaded file')
       .action((cmObj) => {
           let {link, name} = cmObj;
           console.log(link, name)
       });
    program.parse(process.argv);
    

    Let’s go over the above code:

    version indicates what version of our CLI app we are running.

    Read More:  The Concept of Scope in JavaScript

    description provides a description of our app.

    command adds a new command that we can run different programs through. For instance, adding ytd , in this case, allows us to run

    node src/index.js ytd --version

    If we wanted a different app that would say, download videos from Instagram, we might also add

    program.command(‘instd’) //...
    

    And run the code as

    node src/index.js instd --version

    option is used to add different options to our app. The above code might be refactored to read

    program.command('ytd <link>')

    So that downloading would just be as simple as

    ytd https://www.youtube.com/watch?v=zDul1dkWxFk

    However, using arguments makes the code a lot clearer.

    ytd -l https://www.youtube.com/watch?v=zDul1dkWxFk -n “Emptions.mp3”

    Optional arguments can also be indicated using square brackets `[]` and required arguments using ‘<>’

    action is where all the magic happens. Our callback function might look like

    //...
    .action((cmObj) => {
            let {link, name} = cmObj;
            Downloader.download(link, name)
                .then(finishedObj => {
                    console.log("Succeeded.")
                }).catch(err => {
                console.log("Failed.")
            });
       });
    //..

    Note that the commander makes all details about the argument that’s been called available through the callback function.

    The final line parses all arguments we’ve passed for us.

    While this actually works, it’s all a bit boring. Besides, we have no way of knowing whether the program has stalled or is still working, so let’s add some spinners.

    Adding Loading Spinners to Our Node CLI App

    To create a simple CLI spinner, we’re going to use ora.

    Initializing it needs just three lines:

    const ora = require('ora');
    //The initial loading text
    const spinner = ora('Downloading...').start();
    spinner.color = 'yellow';
    

    And our ‘action’ callback can be changed to

    //...
    .action((cmObj) => {
            let {link, name} = cmObj;
            Downloader.download(link, name)
                .then(finishedObj => {
                    //tell the spinner everything is done loading
                    spinner.succeed(`Finished downloading...${finishedObj.videoTitle} in ${finishedObj.states.runtime} seconds`);
                }).catch(err => {
                 //tell the spinner something went wrong.
                spinner.fail("Could not download that file. An Error occurred.")
                console.error(err);
            });
                //recall that we exported the ‘downloader’ object alongside the promise function
            Downloader.downloader.on('progress', function (progressObj) {
                //every time the progress is updated, round off the percentage done to the nearest 2 d.p and set it to the spinner
                spinner.text = `${Number(progressObj.progress.percentage).toFixed(2)}% done`;
            })
        });
    //...

    Now, running our Node CLI app:

    Running Node CLI app
    Running Node CLI app

    Conclusion

    Command line apps have an almost unlimited number of uses, and this app just scratches the surface of all the amazing things you can build using NodeJS and a few related libraries.

    Github: https://github.com/Bradleykingz/node-cli

    JavaScript node Node.js nodejs
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    bradstarart

      Related Posts

      Streamlining Resource Allocation for Enhanced Project Success

      December 18, 2024

      Conducting Effective Post-Project Evaluations: A Guide

      December 16, 2024

      Strategies for Keeping Projects on Track and Meeting Deadlines

      December 10, 2024
      Leave A Reply Cancel Reply

      You must be logged in to post a comment.

      Stay In Touch
      • Facebook
      • Twitter
      • Pinterest
      • Instagram
      • YouTube
      • Vimeo
      Don't Miss
      JavaScript November 25, 2024

      Analyzing Leadership Styles and Their Influence on Project Success

      Effective leadership styles play a pivotal role in project success. By analyzing authoritative, participative, and delegative approaches, organizations can enhance team dynamics, foster collaboration, and drive outcomes, ultimately leading to project excellence.

      Maximizing Lead Generation with LinkedIn InMail Strategies

      December 6, 2024

      Basic Principles and Rules of Our Team

      January 19, 2016

      28 Sample Interview Questions for JavaScript Developers | Theory and Practice

      February 27, 2019

      Categories

      • AI & Automation
      • Angular
      • ASP.NET
      • AWS
      • B2B Leads
      • Beginners
      • Blogs
      • Business Growth
      • Case Studies
      • Comics
      • Consultation
      • Content & Leadership
      • CSS
      • Development
      • Django
      • E-commerce & Retail
      • Entrepreneurs
      • Entrepreneurship
      • Events
      • Express.js
      • Facebook Ads
      • Finance & Fintech
      • Flask
      • Flutter
      • Franchising
      • Funnel Strategy
      • Git
      • GraphQL
      • Home Services Marketing
      • Influencer & Community
      • Interview
      • Java
      • Java Spring
      • JavaScript
      • Job
      • Laravel
      • Lead Generation
      • Legal & Compliance
      • LinkedIn
      • Machine Learning
      • Marketing Trends
      • Medical Marketing
      • MSP Lead Generation
      • MSP Marketing
      • NestJS
      • Next.js
      • Node.js
      • Node.js Lessons
      • Paid Advertising
      • PHP
      • Podcasts
      • POS Tutorial
      • Programming
      • Programming
      • Python
      • React
      • React Lessons
      • React Native
      • React Native Lessons
      • Recruitment
      • Remote Job
      • SaaS & Tech
      • SEO & Analytics
      • Soshace
      • Startups
      • Swarm Intelligence
      • Tips
      • Trends
      • Vue
      • Wiki
      • WordPress
      Top Posts

      JAMstack Architecture with Next.js

      JavaScript March 15, 2024

      23. Уроки Node.js. Домены, “асинхронный try..catch”. Часть 3.

      Programming November 18, 2016

      Error Handling in JavaScript: A Guide to Try/Catch, Throw, and Custom Error Classes

      JavaScript March 30, 2023

      7. Уроки Node.js. Модуль Console

      Programming September 12, 2016

      Subscribe to Updates

      Get The Latest News, Updates, And Amazing Offers

      About Us
      About Us

      Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

      7901 4th St N, Suite 28690
      Saint Petersburg, FL 33702-4305
      Phone: 1(877)SOSHACE

      Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
      Our Picks
      Beginners

      How to customize exceptions in python

      Programming

      The Impact of Integrated Development Environments on Coding

      Programming

      Уроки Express.js . Логгер, Конфигурация, Шаблонизация с EJS. Часть 2.

      Most Popular

      Monthly Digest of the Most Popular JS Github Repositories

      JavaScript

      Node.js Lesson 2: Modules and Exports

      Beginners

      Overview of Bots in Social Media and Messengers

      Programming
      © 2025 Soshace Digital.
      • Home
      • About
      • Services
      • Contact Us
      • Privacy Policy
      • Terms & Conditions

      Type above and press Enter to search. Press Esc to cancel.