【问题标题】:How do you pass a string as an argument to Node from the command-line?如何从命令行将字符串作为参数传递给 Node?
【发布时间】:2016-09-08 10:37:27
【问题描述】:

我是 Node 新手,我正在尝试在 Node 中编写一个命令行工具,它允许您将字符串作为参数传入。

我看到 Node 在使用 process.argv 时似乎会破坏作为数组传入的每个单词。我想知道获取字符串的最佳方法是循环遍历数组来构造字符串还是有其他选择?

假设我有一个简单的程序,它接受一个字符串并简单地将其控制台记录出来。它看起来像这样。

> node index.js This is a sentence.
> This is a sentence.

【问题讨论】:

  • IMO 它不是重复的,因为这个问题专门关于将多字参数作为单个参数传递,而不是一般解析参数。
  • 嘿@whostolemyhat 我可以看到这是如何被视为重复的,但我已经知道如何在 node.js 中传递命令行参数,只是不知道如何将整个字符串传递为一个没有被逐字分解的论点。

标签: node.js


【解决方案1】:

您可以用引号将句子括起来,即

> node index.js "This is a sentence."

另一种选择是在程序中加入文本:

process.argv.shift()  // skip node.exe
process.argv.shift()  // skip name of js file

console.log(process.argv.join(" "))

【讨论】:

  • 非常感谢@MayaLekova,这似乎对我有用。也感谢 cmets 关于.shift() :)
【解决方案2】:

上面的答案使用了过多的代码!
而不是移动它两次使用Array.prototype.splice

// Removes elements from offset of 0
process.argv.splice(0, 2);

// Print the text as usually!
console.log(process.argv.join(' '));

代码摘要

  • 从数组中删除前 2 个元素。
  • 使用[Backspace] 分隔符加入他们。

【讨论】:

    【解决方案3】:

    如果你准备好使用 npm 包。然后使用极简主义。变得容易处理命令行参数。例如,查看他们的 npmjs 网页。希望这会对你有所帮助。

    var args=require('minimist')(process.argv.slice(2),{string:"name"});
    console.log('Hello ' +args.name);
    

    输出是..

    node app.js --name=test
    Hello test
    

    【讨论】:

      【解决方案4】:

      另一个不需要引号或修改process.argv的解决方案:

      const [ node, file, ...args ] = process.argv;
      const string = args.join(' ');
      console.log(string);
      

      输出:

      > node index.js This is a sentence
      > This is a sentence
      

      如果您想了解更多关于我在此处使用扩展运算符 (...) 的方式,请阅读以下内容:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Rest_in_Object_Destructuring

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-10
        • 1970-01-01
        • 2017-07-26
        • 1970-01-01
        • 2013-01-19
        • 2020-08-19
        • 1970-01-01
        • 2023-03-22
        相关资源
        最近更新 更多