Logo

Developer learning path

Node.js

Working with Module Dependencies in Node.js

Working with Module Dependencies

49

#description

In Node.js, modules are the building blocks of a program. They are separate units of functionality that can be imported and used in other files or modules. Node.js provides built-in modules such as http, fs, path, and many more that can be used to perform common tasks. In addition to these built-in modules, Node.js also allows developers to create and use their own custom modules.

Module dependencies refer to the relationships between different modules in a Node.js program. When one module requires functionality from another module, it can specify the dependency by using the require() function. This function takes a string parameter that specifies the path to the module that needs to be loaded. The loaded module can then be used like any other JavaScript object.

For example, let's say we have a file called math.js that exports some mathematical functions:

                    
// math.js

function add(a, b) {
  return a + b;
}

function multiply(a, b) {
  return a * b;
}

module.exports = {
  add,
  multiply
};
                  

We can use this module in another file called main.js by requiring it and then calling its functions:

                    
// main.js

const math = require('./math.js');

const sum = math.add(5, 10);
console.log(sum); // 15

const product = math.multiply(3, 7);
console.log(product); // 21
                  

In this example, main.js depends on math.js because it requires its functions. By using the require() function, we can easily load and use functionality from other modules in a Node.js program.

March 25, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.