var d = domain.create();
function readSomeFile(filename, cb) {
fs.readFile(filename, 'utf8', d.bind(function(er, data) {
// if this throws, it will also be passed to the domain
return cb(er, data ? JSON.parse(data) : null);
}));
}
d.on('error', function(er) {
// an error occurred somewhere.
// if we throw it now, it will crash the program
// with the normal line number and stack message.
});
当然也可以这么使用
var d = domain.create();
function readSomeFile(filename, cb) {
fs.readFile(filename, 'utf8', d.intercept(function(data) {
return cb(null, JSON.parse(data));
}));
}
d.on('error', function(er) {
// an error occurred somewhere.
// if we throw it now, it will crash the program
// with the normal line number and stack message
});
这个函数与domain.bind(callback)几乎一模一样。但是,除了捕捉被抛出的错误外,它还会拦截作为第一参数被传递到这个函数的Error对象。
5)使用log4js 模块记录日志
log4js 是一个非常强大的日志管理工具,在可以看看github这个项目: https://github.com/nomiddlename/log4js-node
6)使用forever 模块来管理nodejs
forever 是服务端管理nodejs 的一个模块,一个命令行工具,能够启动,停止app 应用。forever完全是基于命令行操作,在forever进程管理之下,创建node的子进程,通过monitor监控node子进程的运行情况,一旦文件更新,或者进程挂掉,forever会自动重启node服务器,确保应用正常运行。非常的好用.
可以关注下这个项目:https://github.com/nodejitsu/forever
但是forever 也不是万能的,也由下面这些问题: