在node.js命令行中解析包含正斜杠的字符串

时间:2014-07-28 20:00:06

标签: javascript node.js

您好我正在编写节点js app,我需要通过命令行将路径传递给某个文件。我需要这样做才能进行配置。我知道我可以将所有配置详细信息放在json文件中,然后将其加载到应用程序中。但这是一个特定的要求。

这是我的代码

app.js

  ----
  -----
  console.log(process.argv); 
  ---
  --
 // Start server

现在,当我在节点中运行此文件时:

 node app.js hii

输出

 'hii'

但如果我这样做

node app.js '/samplePath'

我在DOS中得到这个输出:

'\'/samplePath\''

我在Git Bash中得到了这个输出:

'C:/Program Files/Git/samplePath'

我如何获得' / samplePath'作为输出?我究竟做错了什么?任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:0)

要获取最后一项,请尝试

 process.argv[2].split(/\//).pop();

您必须解析自己的命令行选项。但是,您可以查看此节点模块,以便于您使用。

npm install commander

这是他们的Github页面中的一个例子

var program = require('commander');

program
  .version('0.0.1')
  .option('-p, --peppers', 'Add peppers')
  .option('-P, --pineapple', 'Add pineapple')
  .option('-b, --bbq', 'Add bbq sauce')
  .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')
  .parse(process.argv);