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.

Salman
  • 9,299
  • 6
  • 40
  • 73

2 Answers2

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);
    }
}
Salman
  • 9,299
  • 6
  • 40
  • 73
  • 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 ... – oligofren Nov 28 '17 at 08:13
  • As shown in [nodejs documentation](https://nodejs.org/api/modules.html#requireresolvepathsrequest) the nodejs spec includes functions `require.resolve(...)` and `require.resolve.paths(...)`. Don't know if those get used internally or not. – Craig Hicks Jan 03 '22 at 19:44
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

Community
  • 1
  • 1
Krasimir
  • 13,306
  • 3
  • 40
  • 55
  • 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. – Salman Nov 11 '13 at 10:49
  • What about http://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. – Krasimir Nov 11 '13 at 10:52
  • 2
    `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. – Salman Nov 11 '13 at 10:54