Working with Nodejs modules

Let’s look at some aspects of working with modules in Node.js. First of all, it should be noted that plug-ins are cached. In particular, the file https://github.com/nodejs/node/blob/master/lib/internal/modules/cjs/loader.js contains the following lines:

 
var filename = Module._resolveFilename(request, parent, isMain);

  var cachedModule = Module._cache[filename];
  if (cachedModule) {
    updateChildren(parent, cachedModule, true);
    return cachedModule.exports;
}

This, on the one hand, increases productivity, and on the other hand, it can create some problems if we do not take this aspect into account. For example, let’s take the project from the previous topic, where the greeting.js module is included in the main app.js file . Let ‘s change the greeting.js file as follows:

 
module.exports.name = "Alice";

There is only one line defined in the file that sets the name property.

Let’s change the app.js file code :

 
var greeting1 = require("./greeting.js");
console.log(`Hello ${greeting1.name}`); //Hello Alice

var greeting2 = require("./greeting.js");
greeting2.name="Bob";

console.log(`Hello ${greeting2.name}`); // Hello Bob
// greeting1.name has also changed
console.log(`Hello ${greeting1.name}`); // Hello Bob

Despite the fact that here we get the module twice using the require function, both variables – greeting1 and greeting2 will point to the same object.

Module structure

Often, application modules form some kind of separate sets or areas. Such sets of modules are best placed in separate directories. For example, let’s create a welcome subdirectory in the application directory and create three new files in it:

  • index.js
  • morning.js
  • evening.js

As a result, the general structure of the project will look like this:

welcome

  •           index.js
  •           morning.js
  •           evening.js
  • app.js
  • greeting.js

In the morning.js file, put the following line:

 
module.exports = "Good morning";

Let’s change the evening.js file in the same way :

 
module.exports = "Good evening";

These two files define the hello messages depending on the time of day.

And define the following code in the index.js file:

  
const morning = require("./morning");
const evening = require("./evening");

module.exports = {
    getMorningMessage : function(){ console.log(morning);},
    getEveningMessage : function(){ console.log(evening);}
}

The module defines an object that has two functions for displaying greetings.

Now we use this module in the app.js file :

 
const welcome = require("./welcome");

welcome.getMorningMessage();
welcome.getEveningMessage();

Although there is no such file as welcome.js, if there is a directory in the project that contains a file named index.js, then we can refer to the module by a directory name, as in this case.

Let’s run the application, and both greetings will be displayed on the console: