Node.js全局自定义require函数

7
我正在尝试修改require的方式如下。
require = function (path) {
    try {
        return module.require(path);
    } catch (err) {
        console.log(path)
    }
}

然而,此修改的范围仅限于当前模块。我想要全局修改,所以这个模块所需要的每个模块也将获得相同的require函数副本。
基本上,我想要捕获SyntaxError以知道哪个文件有问题。我似乎找不到其他选择。如果我将module.require放在try/catch块中,我就能够获得导致SyntaxError的文件名。
2个回答

9

我通过修改 Module 类的原型函数 require 来解决了这个问题。我将其放置在主脚本中,使得所有调用 require 的模块都可以使用。

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);
    }
}

这似乎很有前途,但在Node 8上对我没有起作用。我将修改放在mod.js中,并使用Mocha的--require选项在所有测试文件之前加载它,但遗憾的是... - oligofren
nodejs文档所示,nodejs规范包括函数require.resolve(...)require.resolve.paths(...)。不知道它们是否在内部使用。 - Craig Hicks

0

我不能在每个需要模块的地方都使用try catch,并告诉用户遵循相同的。这就是为什么我希望对用户透明化。 - Salman
关于http://nodejs.org/api/process.html#process_event_uncaughtexception,你可以将其放在主模块中并捕获所有通常发送到控制台的错误。 - Krasimir
2
当你想捕获SyntaxError时,uncaughtException并不是很有用,因为它不会告诉你哪个文件出现了错误。Node只会打印带有错误片段的文件名,而不会在堆栈跟踪中提供该文件。 - Salman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接