📜 ⬆️ ⬇️

Module Basics in Node.js

Any project is more difficult “Hello World” consists of a certain number of files, which carry the code. This gives you the opportunity to structure the project, to make independent parts that can be used in other projects and generally make the code clearer.

So, in Node.js, each such file is a module that can be connected.
The connection is made by calling the require function to which you need to pass the path to the file.

  var authModule = require('./auth'); 

This code connects the authorization module and makes it available through the authModule variable.
')
Depending on which parameter is passed to the require function, the module connection algorithm will differ. So let's look at the principles of connecting modules in Node.js. I note that all this information is available in the documentation .

Node.js comes with several built-in modules, to connect which you just need to specify the module name.

  var http = require('http'); var cluster = reqiure('cluster'); 

It should be noted that built-in modules take precedence over all others, if their name is passed to the require function. So for example, require('http') will always return a built-in module, even if there is a third-party module with the same name or a file with that name. A list of all built-in modules and documentation on them can be found on the site . The sources of these modules can be viewed in the repository of the project .

If the name of the module is transferred and it is not built-in, then the module is connected from the node_modules folder. This folder contains all the modules that have been added using NPM . NPM is a package manager for Node.js, which makes it easy to find and connect third-party modules. At the time of this writing, it already contained 89,503 modules.

To connect the module which is located in node_modules enough to indicate its name.

  var express = require('express'); var async = require('async'); 

Let's consider the situation when such code was called from the '/var/www/demo' folder, then Node.js will try to find the specified modules in the following folders:
     / var / www / demo / node_modules
     / var / www / node_modules
     / var / node_modules
     / node_modules

Node.js recursively, each time moving to the parent folder, will look for the node_modules folder with the necessary module. NPM also makes it possible to install the module globally ( npm install -g MODULE ), then it will be available from any location.

Consider another connection option, if the passed parameter to the require function begins with / , ../ , or ./ , then the file for the connection will occur in the absolute path or relative to the current folder.

  var logger = require('../lib/logger'); var profiler = require('/var/lib/profiler'); 

First, a file with the name exactly corresponding to the specified one will be checked or if such a file is not found, then Node.js will try to connect the file by adding different extensions to the name: .js , .json , and also .node .

Therefore, there is no need to specify a file with the extension, since require('./lib/users.js') and require('./lib/users') connect the same module.

Modules can be so large that it may be necessary to transfer some parts into separate files in order to better organize the module code. And since these files are used only by this module, it is not necessary that they be among the other modules. To solve this problem in Node.js it is possible to organize the module in the form of a folder in which all the module files will be located. To connect such a module, simply pass the path of this folder to the require function.

Imagine that we have modules and one of them logger is presented in the form of a folder with files:
     A─auth.js
     U─user.js
     Lo─logger
         Index─ index.js
         Console console.js
         Package─ package.json
         Config─ config.js
         D─ db.js

The connection of the logger module is that we simply pass the path to this folder:

  var require('./logger'); 

Further Node.js itself will try to determine which of the folder files is the entry point for the module. To begin with, the package.json file will be checked or exists in the folder in which the name of the file to be connected is indicated in the main field.

  { main: "./console.js" } 

In our case, the file './logger/console.js' will be loaded. If there is no package.json file, then Node.js will try to include the './logger/index.js' or './logger/index.node' .

With the connection of the modules finished, now we will consider several interesting points related to them. Regardless of how you connect the module, it is cached immediately after the connection. This means that no matter how many times a module is connected, its code will be executed only once.

This behavior can be changed by deleting it from the cache after each module call.

  delete require.cache[ module ]; 

module is the parameter you passed to the require function to connect the module.

So if you need your module to do something every time it is plugged in, you need to either clear the cache or return the function that you want to call to do the work.

To get the full path where the module was found, you can use the require.resolve function.

  var modulePath = require.resolve('express'); 

This function can be used if it happened to you that modules of different versions are installed in several places and you need to make sure that the correct version is being connected. You need to go to the folder where the file in which the connection is located, run Node.js in the mode of operation from the command line and call the function with the necessary module. Of course, this situation means that you need to revise the structure of the project and it is better to put all plug-ins in the root folder of the project.

This function can also be used if you want to connect one of the module files that is installed via NPM.

  var package = require.resolve('express/package.json'); 

Since you do not know where the node_modules folder with the desired module is located, you can use the fact that Node.js will go through all possible locations of the module.

The require function, in addition to all this, has another useful property, main . It stores the module that was launched from the command line. So from any module you can find out whether this module was launched directly or it was connected as a dependency of another module.

In addition to the require function already discussed, a module object is available in each module . The main objective of this object is to enable the module to return the result of its execution. It can be an object, a function, and a string — any data type.

The module object has a property of exports and it needs to assign everything that you want to return from the module. It is module.exports will return as a result of the module connection.

  module.exports.createUser = function () { return new User(); } 

After connecting the module with this code, the response will be an object with this method.

You can also use a shorter option, the exports variable, which is essentially just a reference to module.exports .

  exports.createUser = function () { return new User(); } 

Since this is a link, there is one important difference between the two options. The result of the module can be returned only through the module.exports object, so if the exports variable is assigned a different value, it will no longer refer to module.exports , which means the module will not return anything.

But the module.exports itself can be changed. Instead of an object, for example, you can return a function, and then the result of the module’s work will not be an object with a method in the form of a certain function, but a function itself.

With the module you can also find out or this module is launched from the command line. To do this, check the module.parent property - it must be undefined .

I think this information will be enough to work with modules in Node.js. I also recommend getting acquainted with NPM , since you will have to deal with it in every project on Node.js.

Source: https://habr.com/ru/post/233827/


All Articles