简体   繁体   English

命令行参数问题-跳过可选功能参数?

[英]Command line argument question--Skipping optional function parameters?

I am in the middle of learning command line arguments. 我正在学习命令行参数。 What I want to do is print out my script that says "Hello, World" and on the CLI, if you type down 我想做的是,如果您键入以下内容,请在CLI上打印出我的脚本“ Hello,World”

node helloworld (name)

it will print out Hello, (name) instead. 它将打印出Hello, (name) And if no name input, it will output Hello, World by default. 如果没有输入名称,则默认情况下将输出Hello, World

I basically did that but I was wondering, is there any way I can just type 我基本上是这样做的,但我想知道,我有什么方法可以打字

node helloworld (yourname) 

INSTEAD of going through the hassle of typing 避免经历打字的麻烦

node helloworld name (yourname)

 function getArgument(argument){ var index = process.argv.indexOf(argument); return (index === -1) ? null : process.argv[index+1]; } var name = getArgument('name'); var message = name ? "Hello, " + name : "Hello, world."; console.log(JSON.stringify(message)); 

Image link on the bottom to show you what I'm talking about. 底部的图片链接可向您展示我在说什么。 Just want to type helloworld (actualname) instead of helloworld name (actualname): 只想输入helloworld(实际名称)而不是helloworld名称(实际名称):

点击图片

Sure, just always take the first argument: 当然,请始终接受第一个参数:

 let name = process.argv[2];

In your case argv looks like this: 在您的情况下, argv如下所示:

 ["node", "helloworld", "(name)"]

therefore you can just access the third one to get the name. 因此,您只需访问第三个名称即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM