7

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.

2 Answers 2

9

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);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

this seemed promising, but it did not work for me on Node 8. I put the modification in a mod.js and used Mocha's --require option to load it before all test files, but alas ...
As shown in nodejs documentation the nodejs spec includes functions require.resolve(...) and require.resolve.paths(...). Don't know if those get used internally or not.
0

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

3 Comments

I can't use a try catch everywhere I require a module. and tell users to follow the same. That's why I want to make it transparent to the users.
What about nodejs.org/api/process.html#process_event_uncaughtexception. You may put this in your main module and catch all those errors, which are normally send to the console.
uncaughtException is not much helpful when you want to catch SyntaxError as it won't give you the filename which has the error. Node just prints the filename with a snippet of the erroneous file. It doesn't give that file in the stacktrace.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.