文章目录
  1. 1. readline
  2. 2. inquirer
  3. 3. 应用的图形文案

node 中经常会涉及到一些shell的操作,node提供相应的api去写shell程序
process.argv 获取命令行输入的参数
node社区提供了很多对node提供的api封装的api,还有我们经常-g install的package执行的时候都会一个很牛逼的图形有么有,怎么搞的呢?yosay?

readline

readline是node内置的一个与命令行窗口进行交互的一个模块,
主要功能就是询问输入或者通过completer 进行提示
demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
demo-1
var rl = readline.createInterface({
input:process.stdin,
output:process.stdout,
});

rl.question("give me your page id?\n",function(answer){
console.log(answer);
rl.close();
});
api-2
rl.on('line',function(res){
var res = res;
rl.close();
})
.on('close', function () {
console.log('command close ')
});

inquirer

readline可以解决大部分问题,但是没有提供类似web 中select option那种封装
就像yo generator中那个option通过键盘选择的那些东东,经过我不懈的找,终于找到
还不错的库,以下demo利用promise的实现库q进行一层封装,更多的demo

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
26
27
28
29
30
31
32
33
34
35
36
37
/**
* 用 实现promise的q模块实现异步的包装
*
*/

var Q = require('q');
var prompt = require('prompt');
function syncPrompt(callback) {
var deferred = Q.defer();
prompt.get([{
name: 'name',
description: 'Your name',
type: 'string',
required: true
}, {
name: 'surname',
description: 'Your surname',
type: 'string',
required: true,
message: 'Please dont use the demo credentials',
conform: function(surname) {
var name = prompt.history('name').value;
return (name !== 'John' || surname !== 'Smith');
}
}], function(err, results) {
if (err) {
deferred.reject(err);
}
else {
deferred.resolve(results);
}
});
return deferred.promise.nodeify(callback);
}

syncPrompt().done(function (data) {
console.log(data);
});

应用的图形文案

chalk 一个很容易改变输出字符串的颜色的库,很方便
yosay yo generator 中输入的那个yo man的图形,之前不怎么了解这个东西
在项目中引入了,被同事吐槽为啥用yo man的图形,经他提醒去往上各种搜,github
中这种库不多,而且图形文案较为单一,还有的是通过选用图片来展示的,用图片来解决的
两个库,我没试过,mark说不定以后用的着呢,imaging 还有picture-tube
最后找到一个输出很多图形字符的应用,不是用node实现的,通过拷贝图形然后存入txt中,然后fs读取在利用正则替换
利用图形的颜色

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
26
27
28
var fs = require('fs');
var chalk = require('chalk');
var path = require('path');
function say() {
console.log(chalk.red(path.join(__dirname,'ascii.txt')));
var str = fs.readFileSync(path.join(__dirname,'ascii.txt')).toString();
str = str.replace('(.)(.)', chalk.red('(.)(.)'));
str = str.replace('Bravo H5 Gen!', chalk.green('Bravo H5 Gen!'));
str = str.replace("\\\\\\///", chalk.yellow("\\\\\\///"));
console.log(str);
}

exports.say = say;

ascii.txt =>

\\\///
/ _ _ \
(| (.)(.) |)
.---.OOOo--()--oOOO.---.
| |
| Bravo H5 Gen! |
| |
'---.oooO--------------'
( ) Oooo.
\ ( ( )
\_) ) /
(_/

文章目录
  1. 1. readline
  2. 2. inquirer
  3. 3. 应用的图形文案