Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 2, 2021 08:34 pm GMT

How to accept command line arguments in Node.js scripts?

How to accept command line arguments in Node.js scripts?How to accept command line arguments in Node.js scripts?

In this short blog post, were going to see how we can write a Node.js script that accepts command line arguments and named arguments.

As we know in any Node.js script we have an object called process which contains a lot of information about the current running process from environment variables to PID and etc...

One of the available keys in process object is argv and we can easily access it via process.argv.

The two first items are Node.js executable path and JavaScript file path followed by provided command-line arguments unless you run it in an interactive Node.js shell.

// From script file named main.js  console.log(process.argv)  [ '/usr/bin/node', '/home/mmoallemi/main.js' ]  // From interactive node   node  Welcome to Node.js v15.14.0.  Type ".help" for more information.  > process.argv  [ '/usr/bin/node' ]

We should use process.argv.slice(2) instead:

node main.js first second third  ~    node main.js  first second third  [    'first',    'second',    'third'  ]

Great! So far we have achieved to pass positional arguments to our script but if we want to use named arguments or some kind of flags?

node main.js extract --input=test.txt --output=results.txt  [    'extract',    '--input=test.txt',    '--output=results.txt'  ]

We passed one positional argument and two named arguments, we can go ahead and clean the values and split them by = and this kind of stuff, but let's do it right.

Install minimist using your favorite package manager, I use yarn:

yarn add minimist

and then pass arguments to minimist to parse it:

// node main.js extract --input=test.txt --output=results.txt  // main.js script  const minimist = require('minimist')  const args = process.argv.slice(2)  const parsedArgs = minimist(args)  console.log('Parsed Arguments:', parsedArgs)  console.log('Input:', parsedArgs.input)  console.log('Output:', parsedArgs.output)  console.table(parsedArgs)

Enjoy the results!

Parsed Arguments: { _: [ 'extract' ], input: 'test.txt', output: 'results.txt' }  Input: test.txt  Output: results.txt     (index)               Values             _     'extract'                    input               'test.txt'      output              'results.txt'   

Happy scripting!

Originally published at https://mmoallemi99.com on May 2, 2021.


Original Link: https://dev.to/mmoallemi99/how-to-accept-command-line-arguments-in-node-js-scripts-b6b

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To