I have a module with some initialization code inside. The init should be performed when the module is loaded. At the moment I'm doing it like this:
// in the module exports.init = function(config) { do it } // in main var mod = require('myModule'); mod.init(myConfig)
That works, but I'd like to be more concise:
var mod = require('myModule').init('myConfig')
What should init
return in order to keep mod
reference working?
When require function receive the module name as its input, It first tries to load core module. If path in require function begins with './' or '../' It will try to load developer module. If no file is find, it will try to find folder with index.
“Require” is built-in with NodeJS require is typically used with NodeJS to read and execute CommonJS modules. These modules can be either built-in modules like http or custom-written modules. With require , you can include them in your JavaScript files and use their functions and variables.
Create a package.json file, on the command line, in the root directory of your Node. js module, run npm init : For scoped modules, run npm init --scope=@scope-name. For unscoped modules, run npm init.
If the module is native, it calls the NativeModule. require() with the filename and returns the result. Otherwise, it creates a new module for the file and saves it to the cache. Then it loads the file contents before returning its exports object.
You can return this
, which is a reference to exports
in this case.
exports.init = function(init) { console.log(init); return this; }; exports.myMethod = function() { console.log('Has access to this'); }
var mod = require('./module.js').init('test'); //Prints 'test' mod.myMethod(); //Will print 'Has access to this.'
Or you could use a constructor:
module.exports = function(config) { this.config = config; this.myMethod = function() { console.log('Has access to this'); }; return this; };
var myModule = require('./module.js')(config); myModule.myMethod(); //Prints 'Has access to this'
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