nodejs传递参数
How to parse command line arguments
Passing in arguments via the command line is an extremely basic programming task, and a necessity for anyone trying to write a simple Command-Line Interface (CLI). In Node.js, as in C and many related environments, all command-line arguments received by the shell are given to the process in an array called argv
(short for 'argument values').
Node.js exposes this array for every running process in the form of process.argv
- let's take a look at an example. Make a file called argv.js
and add this line:
console.log(process.argv);
Now save it, and try the following in your shell:
$ node argv.js one two three four five
[ 'node',
'/home/avian/argvdemo/argv.js',
'one',
'two',
'three',
'four',
'five' ]
There you have it - an array containing any arguments you passed in. Notice the first two elements - node
and the path to your script. These will always be present - even if your program takes no arguments of its own, your script's interpreter and path are still considered arguments to the shell you're using.
Where everyday CLI arguments are concerned, you'll want to skip the first two. Now try this in argv.js
:
var myArgs = process.argv.slice(2);
console.log('myArgs: ', myArgs);
This yields:
$ node argv.js one two three four five
myArgs: [ 'one', 'two', 'three', 'four', 'five' ]
Now let's actually do something with the args:
var myArgs = process.argv.slice(2);
console.log('myArgs: ', myArgs);
switch (myArgs[0]) {
case 'insult':
console.log(myArgs[1], 'smells quite badly.');
break;
case 'compliment':
console.log(myArgs[1], 'is really cool.');
break;
default:
console.log('Sorry, that is not something I know how to do.');
}
JS PRO TIP: Remember to break
after each case
- otherwise you'll run the next case too!
//console.log(process.argv); var myArgs = process.argv.slice(2); //console.log('myArgs: ', myArgs); const dateTime = require('date-time'); var currentTime = dateTime({local: true, showTimeZone: true, showMilliseconds: true}); console.log(`${myArgs[0]} at ${currentTime}`)
相关文章
- [转]Nodejs基础中间件Connect
- 「NodeJs进阶」超全面的 Node.js 性能优化相关知识梳理
- Python调用nodejs将html转换为Markdown
- nodejs接收post请求参数
- 两分钟观看 nodejs、 iojs、 npmjs 之间的狗血剧情
- NodeJS-001-Nodejs学习文档整理(转-出自http://www.cnblogs.com/xucheng)
- nodejs进阶(5)—接收请求参数
- 初步了解nodejs
- 使用 NodeJS 更新 MySQL 中的记录
- linux服务器安装nodeJS步骤及踩坑记录(解决node -v报错cannot execute binary file: Exec format error的问题 - 在Linux中安装适用于arm64位的nodejs)以及node环境项目部署
- node基础 ,nodejs的express框架(三)
- webstorm+nodejs+express配置
- Vue开发实例(01)之环境搭建nodejs与运行第一个Vue项目