image

Sascha Depold

Engineering Manager

Blog

Passing arguments/parameters using the node command

I recently wanted to pass some parameters to my .js file just from the commandline using the node command. Because I didn’t found an answer on Google, but in a project on Github, I want to let you know how it works.

Let’s say you have a script named foo.js. Run the following command:

node foo.js myParameter

In your script you can now access the attached parameters with:

process.ARGV

You will get:

[ ‘node’
, ‘/path/to/foo.js’
,’myParameter’
]

I needed something like that, to pass a boolean. The final result was:

# script call:
node my.js —option

# script content:
var foo = (process.ARGV.indexOf(“—option”) > -1)

Also useful could be something like:

# script call:
node my.js —path=/foo/bar/foobar.js

# script content:
var path = “”
process.ARGV.forEach(function(arg) {
if(arg.indexOf(“—path”) == 0)
path = arg.split(“=”)[1]
})
require(“sys”).puts(path)

OK… That’s it for now. Hope it might be useful. :)