Node.js全局定制require函数

Sal*_*man 5 module node.js

我试图修改require这样的

require = function (path) {
    try {
        return module.require(path);
    } catch (err) {
        console.log(path)
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,此修改的范围仅在当前模块中.我想全局修改它,因此require该模块的每个模块也将获得相同的require函数副本.

基本上,我想SyntaxError知道哪个文件有问题.我似乎找不到任何其他选择.如果我把module.requiretry/catch块中,我能得到这引起了文件名SyntaxError.

Sal*_*man 7

我设法通过修改原型函数来解决它requireModule类.我将它放在主脚本中,并且可用于所有required模块.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)