简体   繁体   中英

How can I call a function in command line on Nodejs

I have to write a calculator on a text editor and then call the function with the parameters in Node.js command line. (node index.js sub 3 2 1) My function has to have a list of numbers (min 2). This is my function that I wrote to subtract the numbers:

function sub() {
var d = 0;
for (var i=0; i < arguments.length; i++) {
    d = d + (arguments[i] - arguments[i+1]);
}
return d;}

My question is how i call this function on the command line and show the result.

I tried this, but it doesn't work:

 var sub = console.log(process.argv[sub]);

You need to parse your parameters. process.argv is a numerical array, it contains only integer indexes.

To keep it simple you can just write this:

if(process.argv[2] === 'sub') {
  sub()
}

It should be as simple as, suppose following is calculator.js :

function calc (op1, op2, operation) {
    if (operation === 'sum' || operation === 'add'){
        return op1 + op2;
    }
    else if (operation === 'sub'){
        return op1 - op2;
    }
    else if (operation === 'mul'){
        return op1 * op2;
    }
    else if (operation === 'div'){
        return op1 / op2;
    }
    // expand here more operations if needed
    return 'Not sure what to do!';
}

var result = calc(Number(process.argv[3]), Number(process.argv[4]), process.argv[2]);

console.log(result);

Now Run for addition as:

node calculator.js add 1 2

Run for subtraction as:

node calculator.js sub 1 2

Same way you can pass command input to call file functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM