2016-07-15 120 views
1

我使用此代碼添加-find標誌,但我找不到如何獲取可用變量中的值。從命令行輸入獲取值,命令行參數NPM模塊,node.js/javascript

const commandLineArgs = require('command-line-args') 
const quicksearch = [ 
{name: 'find', alias: 'f',type: String} 
] 

我想在終端實現這一點,-find = github上,然後使用查找標誌的值,在可用的變量,所以可發射它到服務器,我讀過文件,但沒有關於它。在

+0

你還好嗎用'-find github'即。用''替換'=',這是標準的repl arg標誌語法 – Iceman

+0

根據文檔,一個可以有值的標誌需要'='。 – Tom

+0

據我所知,它與空間。看看我的答案。我在我的機器上運行它。它的工作原理 – Iceman

回答

0

運行命令PROMT /慶典等:

node test.js -f github

node test.js --find github

node test.js --find=github

期望輸出:

{ find: 'github' }

服務器/ JavaScript文件(test.js):

var commandLineArgs = require('command-line-args') 

const optionDefinitions = [ 
    { name: 'find', alias: 'f', type: String } 
] 

const options = commandLineArgs(optionDefinitions) 

console.log(options); 

//options.find will be equal to 'github' 
+0

如何從{find:'github'}獲取github。我原本以爲我可以得到它的長度,然後相應地削減,但有沒有更好的方法? – Tom

+0

@Tom是一個json對象。拿起它像'options.find'! – Iceman

+0

@Tom cud u upvote如果它有幫助:D thanx – Iceman

0

我喜歡yargs library

npm i yargs

//in your script.js 

var yargs = require('yargs'); 
var flag = yargs.argv.nameOfFlag; 
//var flag === 'value' 

//equivalent to typing this in terminal: 
--nameOfFlag value 
+0

OP在headine中特別要求'command-line-args'npm模塊 – Iceman

+1

aight ...我的不好。 – hsiung