Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a module when it's required

Tags:

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?

like image 952
georg Avatar asked Nov 06 '14 10:11

georg


People also ask

What happens when we require a module?

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.

Can you use require in a module?

“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.

How do I initialize a node module?

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.

What happens when we require a module in NodeJS?

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.


1 Answers

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' 
like image 96
Ben Fortune Avatar answered Oct 09 '22 01:10

Ben Fortune