Node.js全局定制require函数
我正试图修改这样的require
require = function (path) { try { return module.require(path); } catch (err) { console.log(path) } }
但是,此修改的范围仅在当前模块中。 我想对其进行全局修改,所以每个被这个模块require
的模块也会得到require
函数的相同副本。
基本上,我想捕捉SyntaxError
知道哪个文件有问题。 我似乎无法find任何其他的select。 如果我把try/catch
块中的module.require
,我将能够得到导致SyntaxError
的文件名。
我设法通过修改Module
类的原型函数require
来解决它。 我把它放在主脚本中,它可用于所有require
d模块。
var pathModule = require('path'); var assert = require('assert').ok; module.constructor.prototype.require = function (path) { var self = this; assert(typeof path === 'string', 'path must be a string'); assert(path, 'missing path'); try { return self.constructor._load(path, self); } catch (err) { // if module not found, we have nothing to do, simply throw it back. if (err.code === 'MODULE_NOT_FOUND') { throw err; } // resolve the path to get absolute path path = pathModule.resolve(__dirname, path) // Write to log or whatever console.log('Error in file: ' + path); } }
为什么不在代码中使用try-catch块,并且一旦检查堆栈跟踪发生错误。 看看这些链接
- 如何在Node.js中打印堆栈跟踪?
- http://machadogj.com/2013/4/error-handling-in-nodejs.html