Getting CLI Arguments in NodeJS

A useful feature for passing data to our application.

Getting CLI Arguments in NodeJS

Table of contents

No heading

No headings in the article.

Sometimes we want to pass parameters to our NodeJS application. This can be a situation, especially when we run our codes on the servers or in a local development environment. I know we have a .env file and we should use it almost every time with appropriate helper packages (etc dotenv ). But isn't it good if we could pass our arguments to our application when we are starting it?
Luckily yes we can!
Let's make a simple application that has a only duty to write prime numbers between two numbers, and we will pass our two numbers from CLI.

  1. First, create a primeNumberPrinter.js file.
  2. Now let's add our helper function and main function:

    /*
     * if a number divided by any number
     * smaller than or equal to its square root is not a prime number
     */
    const checkPrime = (num) => {
      if (num <= 1) return false; // Less than 2 is not prime
      for (let i = 2; i <= num ** 0.5; i++) {
        // num ** 0.5: square root of num, can be used also Math.sqrt()
        if (num % i == 0) {
          return false;
        }
      }
      return true;
    };
    
    const printPrimeNumsBetween = (initNum, endNum) => {
      for (let i = initNum; i <= endNum; i++) {
        if (checkPrime(i)) {
          console.log(i);
        }
      }
    };
    
  3. Now let's figure out how to get our arguments from CLI. When we pass arguments to our application, like

    node primeNumberPrinter.js <FirstNum> <SecondNum>
    

    NodeJS will create an argv array in the main process object. We can reach this array in our code like:

    // primeNumberPrinter.js
    ...
    const mainArgumentsArray = process.argv;
    console.log(mainArgumentsArray);
    

    If you console this array by just running our file from CLI,

     node primeNumberPrinter
    

    you see there are already 2 elements, the first one is the NodeJS bin file path, second is our file's(primeNumberPrinter.js) path.

     [
     'C:\\Program Files\\nodejs\\node.exe',
     'C:\\Users\\admin\\Desktop\\info\\primeNumberPrinter.js'
     ]
    

    Our arguments will be added to this array by order as string, and to get our arguments, we should slice from mainArgumentsArray.

    // primeNumberPrinter.js
    ...
    const arguments = mainArgumentsArray.slice(2); // process.argv.slice(2)
    
  4. Add now we have to this line to print to console our prime numbers. Now our code looks like this:

    // primeNumberPrinter.js
    const checkPrime = (num) => {
      if (num <= 1) return false;
      for (let i = 2; i <= num ** 0.5; i++) {
        if (num % i == 0) {
          return false;
        }
      }
      return true;
    };
    
    const printPrimeNumsBetween = (initNum, endNum) => {
      for (let i = initNum; i <= endNum; i++) {
        if (checkPrime(i)) {
          console.log(i);
        }
      }
    };
    const mainArgumentsArray = process.argv;
    const arguments = mainArgumentsArray.slice(2);
    printPrimeNumsBetween(+arguments[0], +arguments[1]);  // + makes number
    
  5. Now when we enter from CLI,

    node primeNumberPrinter 3 9
    3
    5
    9
    

    we can get our result.

Instead of downloading a whole package, we can use this feature for passing some test data, keys, and secrets.

Hope this helps you.

Thank you for reading.