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}`)

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(3768)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2019-12-23 onedrive忽略子文件夹
2019-12-23 git filter-repo
2015-12-23 Hosting Your Own NuGet Feeds
2015-12-23 NuGet学习笔记
2015-12-23 软件版本的处理
点击右上角即可分享
微信分享提示