nodejs渐入佳境[7]-yargs处理命令行参数

yargs用于方便的处理命令行参数。导入yargs包,在项目路径下:

1
> npm install --save yargs

原始文件

app.js:

1
2
3
4
5
6
7
8
const yargs = require('yargs');
console.log('Start app.');

console.log(process.argv);

console.log('yargs',yargs.argv);

var command = process.argv[2];

获取用户输入

打开控制台,在当前目录下输入:

1
> node app.js remove --title="buy book"

输出字符串

1
2
3
4
5
6
7
Start app.
[ '/Users/jackson/.nvm/versions/node/v10.13.0/bin/node',
'/Users/jackson/Desktop/compaign/app.js',
'remove',
'--title=buy book' ]
yargs { _: [ 'remove' ], title: 'buy book', '$0': 'app.js' }
Remove node

app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//打印字符串
const yargs = require('yargs');
const nodes = require('./nodes.js')
console.log('Start app.');

console.log(process.argv);

console.log('yargs',yargs.argv);
const argv = yargs.argv;
var command = process.argv[2];

if(command==='add'){
nodes.addNote(argv.title,argv.body);
}else if(command === 'list'){
nodes.getAll();

}else if(command =='read'){
nodes.getNote(argv.title);
}else if(command=='remove'){
nodes.removeNote(argv.title);
}else{
console.log('command not find');
}

notes.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
console.log('start nodes.js');

var addNote = (title,body)=>{
console.log('Adding note',title,body);
}

var getAll = ()=>{
console.log('Get All notes');
};

var getNote = (title)=>{

console.log('getting note',title);
};

var removeNote = (title)=>{
console.log('Removing note',title);
};

module.exports = {
addNote,
getAll,
getNote,
removeNote
};

测试

打开控制台,在当前目录下输入:

1
> node app.js remove --title="buy book"

输出字符串:

1
2
3
4
5
6
7
8
start nodes.js
Start app.
[ '/Users/jackson/.nvm/versions/node/v10.13.0/bin/node',
'/Users/jackson/Desktop/compaign/app.js',
'remove',
'--title=buy book' ]
yargs { _: [ 'remove' ], title: 'buy book', '$0': 'app.js' }
Removing note buy book

打开控制台,在当前目录下输入:

1
> node app.js add --title="buy book" --body="jonson"

输出字符串:

1
2
3
4
5
6
7
8
9
10
11
12
start nodes.js
Start app.
[ '/Users/jackson/.nvm/versions/node/v10.13.0/bin/node',
'/Users/jackson/Desktop/compaign/app.js',
'add',
'--title=buy book',
'--body=jonson' ]
yargs { _: [ 'add' ],
title: 'buy book',
body: 'jonson',
'$0': 'app.js' }
Adding note buy book jonson