DEV Community

miku86
miku86

Posted on • Updated on

NodeJS: How To Run Scripts From The Terminal & Use Arguments

Intro

So we installed NodeJS on our machine.

Now we want to write a simple script, run it from the terminal & use some commandline arguments.


Write a simple script

  • Open your terminal
  • Create a file named index.js:
touch index.js
Enter fullscreen mode Exit fullscreen mode
  • Add console.log('Hello') into it:
echo "console.log('Hello')" > index.js
Enter fullscreen mode Exit fullscreen mode

Run it from the terminal

  • Run it:
node index.js
Enter fullscreen mode Exit fullscreen mode

Use commandline arguments

  • Update index.js to use the commandline arguments and print them:
echo "const args = process.argv" > index.js 
echo "console.log(args)" >> index.js
Enter fullscreen mode Exit fullscreen mode
  • Run it with an argument:
node index.js miku86
Enter fullscreen mode Exit fullscreen mode
  • We are seeing an array with 3 elements:
[ 
'/usr/bin/node', 
'/home/miku86/index.js', 
'miku86' 
]
Enter fullscreen mode Exit fullscreen mode

args[0] is the path to the executable file,
args[1] is the path to the executed file,
args[2] is the additional commandline argument from step 2.

So if we want to use our additional commandline argument,
we can use it like this in a JavaScript file:

console.log(args[2])
Enter fullscreen mode Exit fullscreen mode

Further Reading

Node process.argv documentation


Questions

  • Do you use the native process or some libraries like yargs? Why?

Oldest comments (3)

Collapse
 
andre000 profile image
André Adriano

Cool article. Last time I had to do a project with node on the terminal I used meow. It helps with flag creation and automatically creates a --help flag.

Collapse
 
shawonashraf profile image
Shawon Ashraf

You can also use yargs for that. I haven't tried meow yet but seems intriguing.

Collapse
 
miku86 profile image
miku86

Hey André & Shawon,

thanks for your feedback.
I usually use yargs & I will check out meow.

After looking at npm trends, I will also take a look at commander.