Modules in Node.js | Backend Mastery with Node.js ๐ | In Hindi | Death Code
What are Modules?
Modules are reusable pieces of code that can be exported from one file and imported into another. They help in organizing code, making it more maintainable and reusable.
Why and When to Use Modules?
Modules are used to encapsulate functionality, making it easier to manage dependencies and avoid global scope pollution. They are particularly useful in large applications where code organization is crucial.
Advantages of Using Modules
- Encapsulation of code
- Reusability
- Improved maintainability
- Better organization of code
How to Install Modules
To install modules, you typically use npm (Node Package Manager). You can install a module by running the following command in your terminal:
npm install <module-name>
Creating Your Own JavaScript File as a Module
To create your own module, create a JavaScript file (e.g., utils.js
) and export functions or variables from it. Hereโs an example:
// utils.js
export function sqr(num) {
return num * num;
}
export function multiply(num) {
return num * 5;
}
export var str = "hello";
export default { sqr, multiply };
Importing Local Files and Installed Modules
Using CommonJS (require)
In Node.js, you can import modules using the require
method. Hereโs how you can import from utils.js
:
// app.js
const utils = require('./utils.js');
console.log('hello, devs');
console.log(utils);
console.log('Number:', utils.sqr(3));
console.log('Number:', utils.multiply(3));
Using ES Modules (import)
To use ES Modules, you can use the import
statement. Hereโs how you can import from utils.js
:
// app.js
import utils, { str, sqr, multiply } from './utils.js';
console.log('hello, devs');
console.log(utils);
console.log(str);
console.log('Number:', sqr(3));
console.log('Number:', multiply(3));
What is npm?
npm (Node Package Manager) is a package manager for JavaScript and is the default package manager for Node.js. It allows developers to install, share, and manage dependencies in their projects.
Alternatives to npm
Some alternatives to npm include:
- Yarn
- pnpm
- bower (less common now)
Each has its own advantages, but npm is widely used and has a large ecosystem.
Which is Best for Use and When?
npm is generally the best choice for most projects due to its extensive library and community support. Yarn is preferred in some cases for its speed and reliability, especially in larger projects.