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 require
d 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
.
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') .
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.
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.
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.
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 require
d 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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With