Bootstrap FreeKB - Node.js - Command line options and flags
Node.js - Command line options and flags

Updated:   |  Node.js articles

Unlike other scripting languages, such as Python, Node.js does not seem to have an obvious way to pass in command line options, flags and arguments on the command line. However, this is still possible using process.argv, but it's definitely clunky and not as elegant as Python.

For example, let's say you have a Node.js script named app.js that contains the following.

process.argv.forEach(function (val, index) {
  console.log(`index = ${index}`)
  console.log(`val = ${val}`)
})

 

And you issue the following command on the command line.

node app.js foo=bar

 

Something like this should be returned.

~]$ node app.js foo=bar
index = 0
val = /usr/local/bin/node-v22.8.0-linux-x64/bin/node
index = 1
val = /home/john.doe/app.js
index = 2
val = foo=bar

 

In this example, index 2 contains foo=bar so let's use an if statement to only deal with index 2.

process.argv.forEach(function (val, index) {
  if (index == 2) {
    console.log(`index = ${index}`)  
    console.log(`val = ${val}`)
  }
})

 

Which should now return the following.

~]$ node app.js foo=bar
index = 2
val = foo=bar

 

And we can split at the = character to get the key and value.

process.argv.forEach(function (val, index) {
  if (index == 2) {
    const items = val.split('=')
    key = items[0]
    value = items[1]
    console.log(`key = ${key}`)
    console.log(`value = ${value}`)
  }
})

 

Which should now return the following.

~]$ node app.js foo=bar
key = foo
value = bar

 

And here is a bit of a more practical example,

var environment = ""
var platform = ""
const valid_environments = ["dev", "stage", "prod"]
const valid_platforms = ["aws", "onprem"]

process.argv.forEach(function (val, index) {
  if (index >= 2) {
    items = val.split('=')

    if (/^env=/i.test(val)) {
      value = items[1]

      if (! valid_environments.includes(value)) {
        console.log(`${value} is NOT a valid environment. The valid environments are => ${valid_environments}`)
        process.exit(1)
      }
      environment = items[1]
    }

    if (/^platform=/i.test(val)) {
      value = items[1]

      if (! valid_platforms.includes(value)) {
        console.log(`${value} is NOT a valid platform. The valid platforms are => ${valid_platforms}`)
        process.exit(1)
      }
      platform = items[1]
    }

  }
})

console.log(`environment => ${environment}`)
console.log(`platform => ${platform}`)

 

Which would be run like this.

~]$ node app.js env=dev platform=onprem
environment = dev
platform = onprem

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter e49e07 in the box below so that we can be sure you are a human.