| 2 min read

如果不是和命令行工具打交道,可能我们很少有机会去用到process模块中的一些方法或者属性。不过如果你要做类似于webpack或者gulp等较为复杂的构建工具,由于bash界面就是和用户直接交流的工具,因此友好的输入输出,完整的提示都非常有必要了。

一张表格大概可以看到process有哪些属性

属性名称 用途
platform 判断当前系统平台
argv 当前进程的命令行参数数组
execPath 当前进程的可执行文件的绝对路径
stdout 指向标准输出
stdin 指向标准输入
stderr 指向标准错误
stderr 指向标准错误

我们可以直接在代码中这样使用

console.log(porcess.platform)
// darwin

使用argv 会返回命令行的数组,我们可以通过数组来获取用户具体的命令

console.log(process.argv);
// [ '/usr/local/bin/node',  '/Users/ali-130257n/www/weex-jackzoo/projects/demo.js', '-p', '-v' ]

一般情况下,我们更想获取最后的一些参数,前面两个不需要,我们可以

let args = process.argv.slice(2);
console.log(args)

// [ '-p', '-v' ]

process 提供的方法有很多。大致我们可以用到的有下面一些。

cwd:返回运行当前脚本的工作目录的路径

abort:立即结束进程

nextTick: 指定下次事件循环首先运行的任务

process 支持的一些事件,通过一些事件,我们可做一些友好的提示或者处理。
uncaughtException:当前进程抛出一个没有被捕捉的意外时,会触发uncaughtException事件

message: 接受来自父进程的消息

rejectionHandled:用于捕获与它关联的promise错误处理并且产生的reject

unhandledRejection: 同理这个便是用于捕获没有与之关联promise错误处理的reject

const unhandledRejections = new Map();
process.on('unhandledRejection', (reason, p) => {
  unhandledRejections.set(p, reason);
});
process.on('rejectionHandled', (p) => {
  unhandledRejections.delete(p);
});

warning: 当前进程产生一个警告的时候出发

process.on('warning', (warning) => {
  console.warn(warning.name);    // Print the warning name
  console.warn(warning.message); // Print the warning message
  console.warn(warning.stack);   // Print the stack trace
});

You Can Speak "Hi" to Me in Those Ways