4

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

iSkore
  • 7,394
  • 3
  • 34
  • 59
John Cooper
  • 41
  • 1
  • 2

4 Answers4

2

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

Rehban Khatri
  • 924
  • 1
  • 7
  • 19
1

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()
feihcsim
  • 1,444
  • 2
  • 17
  • 33
1

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
Tomas Varga
  • 1,432
  • 15
  • 23
0

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

Community
  • 1
  • 1
iSkore
  • 7,394
  • 3
  • 34
  • 59