【问题标题】:How can I call a function in command line on Nodejs如何在 Nodejs 的命令行中调用函数
【发布时间】:2018-03-02 10:48:24
【问题描述】:

我必须在文本编辑器上编写一个计算器,然后在 Node.js 命令行中使用参数调用该函数。 (节点 index.js 子 3 2 1) 我的函数必须有一个数字列表(最少 2 个)。 这是我写的减去数字的函数:

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

我的问题是我如何在命令行上调用这个函数并显示结果。

我试过了,但它不起作用:

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

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    你需要解析你的参数。 process.argv 是一个数值数组,它 仅包含整数索引。

    为了简单起见,你可以这样写:

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

    【讨论】:

      【解决方案2】:

      应该很简单,假设下面是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);
      

      现在运行添加为:

      nodecalculator.js 加 1 2

      运行减法为:

      nodecalculator.js sub 1 2

      您可以通过同样的方式将命令输入传递给调用文件函数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-05-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多