codecamp

Node.js 全局事件

全局异常处理程序

任何全局未处理的异常都可以通过监听进程上的“uncaughtException”事件来拦截。

为了方便记录错误,使用错误代码退出此过程。

process.on("uncaughtException", function (err) {
   console.log("Caught exception: ", err);
   console.log("Stack:", err.stack); 
   process.exit(1); 

}); 
// Intentionally cause an exception, but don"t try/catch it. 
nonexistentFunc(); 
console.log("This line will not run."); 

如果任何事件发射器引发`error`事件,并且没有为此事件预订事件发射器的监听器,则在进程上也会引发`uncaughtError`事件。

退出

exit事件在进程即将退出时发出。

在这一点上没有办法中止退出。事件循环已经在拆卸,所以你不能在此时执行任何异步操作。

process.on("exit", function (code) {
    console.log("Exiting with code:", code); 
}); 

process.exit(1); 

事件回调在进程退出的退出代码中传递。

这个事件最有用目的是用于调试和记录。

信号

Node.js过程对象也支持UNIX的信号概念,这是一种进程间通信的形式。

要在终端中处理Ctrl+C组合键,添加监听器订阅 SIGINT (信号中断)事件,监听器被调用,你可以选择是否要退出进程(process.exit)或继续执行。

以下代码处理Control-C事件,并选择继续运行并在五秒钟后退出。

setTimeout(function () {
    console.log("5 seconds passed. Exiting"); 
}, 5000); 
console.log("Started. Will exit in 5 seconds"); 
process.on("SIGINT", function () {
    console.log("Got SIGINT. Ignoring."); 
}); 
Node.js events事件模块
Node.js 事件处理程序
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }