nodejs(一)process模块

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

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

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

1 process.on('exit', function () {
2   setTimeout(function () {
3     console.log('This will not run');
4   }, 100);
5   console.log('exit');    
6 });

//结果打印出exit

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

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

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

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

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

Caught exception: ReferenceError: nonexistentFunc is not defined
This will still run.
原文地址:https://www.cnblogs.com/yuyutianxia/p/3271733.html