Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js customize require function globally

Tags:

node.js

module

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.

like image 934
Salman Avatar asked Nov 11 '13 09:11

Salman


People also ask

Do you need to use require () to get the global object?

The require module, which appears to be available on the global scope — no need to require('require') . The module module, which also appears to be available on the global scope — no need to require('module') .

Why is require () used in NodeJS?

In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.

Can we use import instead of require in NodeJS?

You can now start using modern ES Import/Export statements in your Node apps without the need for a tool such as Babel. As always, if you have any questions, feel free to leave a comment.

What is global function in NodeJS?

Node. js global objects are global in nature and they are available in all modules. We do not need to include these objects in our application, rather we can use them directly. These objects are modules, functions, strings and object itself as explained below.


1 Answers

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);
    }
}
like image 128
Salman Avatar answered Sep 20 '22 13:09

Salman