nodejs(一)process模块

时间:2022-03-19 23:09:50

1.process是一个全局进程,你可以直接通过process变量直接访问它。

  process实现了EventEmitter接口,exit方法会在当进程退出的时候执行。因为进程退出之后将不再执行事件循环,所有只有那些没有回调函数的代码才会被执行。

在下面例子中,setTimeout里面的语句是没有办法执行到的。

 process.on('exit', function () {
  setTimeout(function () {
    console.log('This will not run');
  }, 100);
  console.log('exit');
}); //结果打印出exit

2.在你接触node之后,你就会发现那些影响了主事件循环的异常会把整个node进程宕掉的。

这会是相当严重的问题,所以process提供了另外一个有用的事件uncaughtException来解决这个问题,他会把异常抓取出来供你处理。

 process.on('uncaughtException', function (err) {
  console.log('Caught exception: ' + err);
});
setTimeout(function () {
  console.log('This will still run.');
}, 500);
// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
console.log('This will not run.');

我们来看上面的例子,我们注册了uncaughtException事件来捕捉系统异常。执行到nonexistentFunc()时,因为该函数没有定义所以会抛出异常。

因为javascript是解释性的语言,nonexistentFunc()方法上面的语句不会被影响到,他下面的语句不会被执行。所以他的执行结果如下:

Caught exception: ReferenceError: nonexistentFunc is not defined
This will still run.