Node.js Masterclass
High-Performance Backends01.Home02.Introduction03.Environment Setup04.Modules & Exports05.File System (fs)06.Path & OS Modules07.Buffer & Streams08.Events & EventEmitter09.HTTP Module10.NPM & Package.json11.Express.js Fundamentals12.Express Routing13.Express Middleware14.RESTful API Development15.Asynchronous Programming16.Error Handling17.Database with Mongoose18.Authentication with JWT19.Environment Variables20.Testing with Jest21.Deployment & PM2
Modules & Exports
Modules are the building blocks of any Node.js application. They allow you to break your code into separate files, making it more organized, reusable, and maintainable.
1. What is a Module?
In Node.js, every file is treated as a separate module. Variables, functions, and classes defined in one file are private to that file unless explicitly "exported."
2. CommonJS (Traditional)
This is the default module system in Node.js. It uses module.exports to export and require() to import.
Exporting (math.js):
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
module.exports = { add, subtract };Importing (app.js):
const math = require('./math');
console.log(math.add(5, 3)); // 83. ES Modules (Modern)
Standardized in ES6, this system is now natively supported in Node.js using the .mjs extension or by adding "type": "module" to your package.json.
Exporting:
export const multiply = (a, b) => a * b;
export default function welcome() {
console.log("Welcome to ES Modules!");
}Importing:
import welcome, { multiply } from './utils.js';
welcome();
console.log(multiply(4, 2)); // 8Warning: You cannot use
require inside an ES Module, and vice versa, without specific configuration. It's best to stick to one system per project.