John Cooper
John Cooper

Reputation: 51

Run a JS function with arguments from the Command Line

I have a javascript file with a function that receives an Array with random numbers and returns a solution, I need to be able to run this function from the Command Line.

What i want is to be able to type something like: myFunction 1,2,3,4,5,6,7

Upvotes: 5

Views: 9853

Answers (4)

iSkore
iSkore

Reputation: 7553

The demo

'use strict';

function add( n1, n2 ) {
    return n1 + n2;
}

function subtract( n1, n2 ) {
    return n1 - n2;
}

On browser:

Invoke the function calling:

window.add( 1, 2 );
window.subtract( 1, 2 );

With Node.js:

Invoke the function from the command line:

Note: this is only for development purposes

Do not use eval in production

Put this at the bottom of the file:

eval( process.argv[ 2 ] )

And call your function by doing:

node index.js "add( 1, 2 )"
node index.js "subtract( 1, 2 )"

with your terminal

Upvotes: 0

Tomas Varga
Tomas Varga

Reputation: 1440

Considering NodeJS, create a wrapper script where your script with myFunction is imported (would have to export it with module.exports.myFunction = myFunction in your original file first), then pass it the arguments from process.args, skipping the 1st element (as it's always path of the script):

// argsrun.js
var myFunction = require('thescript.js').myFunction;
myFunction(process.args.slice(2));

and call it from CLI:

node argsrun.js 1 2 3 4

Upvotes: 1

Rehban Khatri
Rehban Khatri

Reputation: 954

You can use Node.js for JavaScript CLI.

You can pass arguments like this -

node calendar.js --year 2020 --month 7

Using above command process.argv[] array will have this value -

['node', 'calendar.js', '--year', '2020', '--month', '7']

In your code, it can be read using array process.argv[] like this -

var x = +process.argv[2];  //For third argument
var y = +process.argv[3];  //For fourth argument

1st and 2nd arguments will be node and calendar.js respectively

Upvotes: 3

feihcsim
feihcsim

Reputation: 1552

Export the function from your file:

module.exports = function myFunction(){
    // ...
}

and then use that exported module in your command line with Node's REPL by first running node then executing:

> const myFunction = require('./path/to/the/file-containing-myFunction')`

after which you'll be able to use myFunction like so:

> myFunction()

Upvotes: 1

Related Questions