nodejs local modules Node.js

www.igif‮dit‬ea.com

In Node.js, you can create your own local modules to encapsulate and reuse code within your application. Local modules are modules that are not part of the Node.js core modules and are not installed globally using a package manager like NPM. Instead, they are defined within your application and can be imported and used like any other module.

To create a local module, you can simply create a new .js file and define your module's functionality using the module.exports object. For example, suppose you have a file called utils.js that defines a function that generates a random number:

function getRandomNumber(max) {
  return Math.floor(Math.random() * max);
}

module.exports = {
  getRandomNumber
};

You can then import this module into your main application file using the require() function and use its functionality:

const utils = require('./utils');

console.log(utils.getRandomNumber(100)); // Output: A random number between 0 and 100

In this example, we import the utils module from the utils.js file using the require() function, and then use its getRandomNumber() function to generate a random number between 0 and 100.

Local modules can also have dependencies on other local or external modules, and can be organized into subdirectories to further organize and encapsulate code. When importing a module that is located in a subdirectory, you need to specify the relative path to the module file.