【问题标题】:get command line argument verbatim in nodejs在nodejs中逐字获取命令行参数
【发布时间】:2019-06-20 19:22:44
【问题描述】:

我想完全按照他们输入的方式获取用户命令。唯一允许的区别是' 可以代替",反之亦然。

例如,如果用户键入。

node test.js git commit -m "first message"

我想在控制台上记录以下任何一个。

You typed: git commit -m 'first message' //line A
You typed: git commit -m "first message" //line B

但是有不可接受的:

You typed: "git" "commit" "-m" "first message" //line C
You typed: 'git' 'commit' '-m' 'first message' // line D

正如您在上面看到的,引号可以与用户提供的不同(' 可以替换 ",反之亦然,如 B 行),但不能错位(如 C 和 D 行) .希望这很清楚。

编辑: 编辑了整个问题以避免混淆。

【问题讨论】:

  • 引号在传递给节点之前由 shell 解释,因此如果没有显式转义和引用整个命令(例如 "git commit -m \"first message\""),您可能无法执行您想要的操作。跨度>
  • 乔...我进行了编辑。你能告诉我这是否可能吗?
  • 编辑不清楚,请准确说明您想要什么而不是不可接受的结果
  • 我编辑了这个问题。希望这很清楚。

标签: node.js


【解决方案1】:

您的问题不是很清楚,但假设您只想记录收到的参数,您可以这样做:

let args = [];
// Get program arguments
process.argv.forEach((val, index) => {
if (index > 1)
    args.push(val);
});
let command = args.join(" ");
console.log("You typed: ", command);

但请注意,在打印输出时,您会丢失引号,正如 cmets 中的 @Joe 所说,shell 在将它们传递给节点之前会将它们转义

【讨论】:

    猜你喜欢
    • 2011-12-05
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    • 2021-01-05
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 2014-01-03
    相关资源
    最近更新 更多