DEV Community

Romulo Gatto
Romulo Gatto

Posted on • Updated on

Node.js Modules and npm

Node.js Modules and npm

Node.js is a powerful, open-source JavaScript runtime environment that allows developers to write server-side applications using JavaScript. One of the key features of Node.js is its modular approach, which helps in organizing code into reusable components known as modules.

In this guide, we will explore the concepts of Node.js modules and npm (Node Package Manager) and learn how to use them effectively in your projects.

What are Node.js Modules?

Modules in Node.js are self-contained pieces of code that can be imported or exported for reusability. These modules help break down larger applications into smaller, manageable chunks, making development faster and more maintainable.

To create a module in Node.js, you simply need to define a file with ".js" extension containing your desired functionality. For example, let's say you want to create a module called "utils" with various utility functions:

// utils.js

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

function subtract(a, b) {
  return a - b;
}

module.exports = {
  add,
  subtract
};
Enter fullscreen mode Exit fullscreen mode

In the above example, we have defined two functions (add and subtract) inside utils.js, and then exported them using the module.exports statement for other parts of our application to consume.

Using Modules in Your Application

Once you have created your module(s), you can easily import them into your main application file using the require() function. Let's assume our main application file is called "app.js":


javascript
// app.js

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

console.log(utils.add(5, 3)); // Output: 8
console.log(utils.subtract(10
Enter fullscreen mode Exit fullscreen mode

Top comments (0)