🔍 Introduction
Node.js has two main ways to include code from other files or packages: require() and import. They both help you use functions, classes, or variables from other files, but they work differently because they come from different JavaScript module systems.
📜 What is require()?
require() is the older way of importing code in Node.js. It is based on the CommonJS module system, which Node.js originally used.
-
Loads modules synchronously (one after another).
-
Can be used anywhere in the code.
-
Works in all Node.js versions by default.
Example:
// Using require()
const fs = require('fs');
const data = fs.readFileSync('example.txt', 'utf8');
console.log(data);
Explanation: Here, require() loads the fs module to read a file.
🌐 What is import?
import is the newer way of including code, following the ES Modules (ESM) standard.
- Loads modules asynchronously by default.
- Must be used at the top of the file.
- Needs "type": "module" in package.json or .mjs file extension.
Example:
// Using import
import fs from 'fs';
const data = await fs.promises.readFile('example.txt', 'utf8');
console.log(data);
This uses import with async/await to read a file.
⚖ Key Differences Between require() and import
Feature |
require() (CommonJS) |
import (ESM) |
Module System |
CommonJS |
ES Modules |
Loading Type |
Synchronous |
Asynchronous |
Placement in Code |
Anywhere |
Top-level only |
Default in Node.js |
Yes |
Needs configuration |
Performance |
Slightly slower for large files |
Faster in some cases |
📊 When to Use Which?
- Use require() if you are working on older Node.js projects or need compatibility with existing CommonJS modules.
- Use import for modern projects, especially if you are writing code that needs to run both in Node.js and browsers.
📝 Summary
In Node.js, require() belongs to the CommonJS module system and loads modules synchronously, while import belongs to ES Modules and loads modules asynchronously. require() is older, widely supported, and flexible, while import is modern, faster in certain cases, and aligns with JavaScript standards used in browsers. Choosing between them depends on your project setup, compatibility needs, and performance goals.