Nodejs

From John Freier
Jump to: navigation, search

How to use Require

Require will cache objects after it calls them, kind of like a singleton pattern.

To build out an object that require can grab there are a couple of different ways.

The following way will create an object based on a function so it can have private variables.

example.js

 const exampleService = (function() {
   const self = this;
 
   self.print = function() {
     console.log('...');
   }
 
   return this;
 
 })();
 module.exports = exampleService;


Another way is to create a kind of JSON object with functions.

example.js

 const exampleService = {
   name: 'example',  
   print: function() {
     console.log('...');
   }
 
 };
 module.exports = exampleService;


Then you can call them from your script like so.

 const exampleService = require('./service/example');
 exampleService.print();

You don't need to add the .js but I think you have to start with '.' directory.