Salman
Salman

Reputation: 9447

Node.js customize require function globally

I am trying to modify require like this

require = function (path) {
    try {
        return module.require(path);
    } catch (err) {
        console.log(path)
    }
}

However, scope of this modification is only in the current module. I want to modify it globally, so every module that is required by this module will also get the same copy of require function.

Basically, I want to catch SyntaxError to know which file has problem. I can't seem to find any other alternative. If I put module.require in try/catch block, I'll be able to get the file name which caused SyntaxError.

Upvotes: 7

Views: 4061

Answers (2)

Salman
Salman

Reputation: 9447

I managed to solve it by modifying prototype function require of Module class. I put this in the main script and its available to all the required modules.

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

Upvotes: 9

Krasimir
Krasimir

Reputation: 13529

Why don't you use a try-catch block inside your code and once an error occurs to check the stack trace. Check out these links

Upvotes: 0

Related Questions