Importing and Exporting in Node.js
Importing and Using
To import a function from a module, use the require function. Here's an example:
// In file app.js
const greet = require('./greet');
console.log(greet('World')); // Output: Hello, World!Exporting Multiple Functions/Variables
To export multiple functions or variables, attach them to the module.exports object:
// In file utils.js
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
module.exports = { add, subtract };Importing Multiple Exports
To import multiple exports from a module, use destructuring:
// In file app.js
const { add, subtract } = require('./utils');
console.log(add(5, 3)); // Output: 8
console.log(subtract(5, 3)); // Output: 2How require Works
When you use require to import a module, Node.js executes the code in the module file. Only the properties of module.exports are exposed to the importing file.
// In file data.js
const secret = 'hidden';
const publicData = 'visible';
module.exports = publicData;// In file app.js
const data = require('./data');
console.log(data); // Output: visible
console.log(secret); // Error: secret is not definedmodule.exports = {} Explained
module.exports is initialized as an empty object by default. You can attach properties to it or overwrite it entirely:
// Attaching properties
let x = 10;
module.exports.x = x;
// Overwriting
module.exports = {
greet: function(name) {
return `Hello, ${name}`;
}
};CommonJS vs. ES Modules
CommonJS (.js)
- Uses
require()andmodule.exports - Synchronous module loading
// common.js
// function print() {
// return 'Hello from CommonJS!';
// }
// const message = 'This is a CommonJS module';
// module.exports = { print, message };
// or
console.log('Start loading common.js (CommonJS)');
const start = Date.now();
while (Date.now() - start < 3000) {
// Simulate 3 seconds blocking
}
console.log('Finished loading common.js (CommonJS)');
module.exports = {};
// app.js
// const msg = require('./common');
// console.log(msg());
// console.log('This is a app.js')
// console.log('this is sysnchronous module loading');
// or
console.log('Before require');
require('./common.js'); // BLOCKS the code for 3 seconds
console.log('After require');
ES Modules (.js)
- Uses
importandexport - Asynchronous module loading
// module.js
// export function greet(name) {
// return `Hello, ${name}!`;
// }
// export const message = 'This is an ES Module';
// or
// delay.js
console.log('Start loading delay.js (ESM)');
const start = Date.now();
while (Date.now() - start < 3000) {
// Simulate 3 seconds blocking
}
console.log('Finished loading delay.js (ESM)');
const message = 'Hello from delay.js';
export default message; // ✅ default export
// or data.js
const defaultMsg = 'This is the default message';
export default defaultMsg;
export const author = 'PD';
export const topic = 'ES Modules';
// app.js
// import { greet, message } from './module.js';
// console.log(greet('World')); // Hello, World!
// console.log(message); // This is an ES Module
// console.log('This is app.js');
// console.log('This is asynchronous module loading');
// or
// app.js
import delay from './delay.js';
console.log('Before anything');
console.log('Delay:', delay);
console.log('After import');
// or data.js
import msg, { author, topic } from './data.js';
console.log(msg); // This is the default message
console.log(author); // PD
console.log(topic); // ES ModulesKey Differences
| Feature | CommonJS | ES Modules |
|---|---|---|
| Syntax | require(), module.exports | import, export, from |
| Strict Mode | Non-strict by default | Always in strict mode |
| Loading | Synchronous | Asynchronous |
| Use Case | Node.js (default) | React, Angular (default) |
| Age/Standard | Older legacy system | Modern standard |
CommonJS Example (Non-strict, Sync, Node.js Default)
// greet.js
function greet(name) {
return `Hello, ${name}`;
}
module.exports = greet;
// app.js
const greet = require('./greet');
console.log(greet('World')); // Output: Hello, World!ES Modules Example (Strict, Async, Used in Frontend)
// greet.js
export function greet(name) {
return `Hello, ${name}`;
}
// app.js
import { greet } from './greet.js';
console.log(greet('World')); // Output: Hello, World!| Feature | CommonJS | ES Modules |
|---|---|---|
| Syntax | require, module.exports | import, export, from |
| Loading | Synchronous | Asynchronous |
| Use Case | Legacy code, Node.js | Modern JS Projects (React, Angular) |
| Strict Mode | Non-strict by default | Always strict |
| Age | Older, legacy | New standard |
Synchronous vs Asynchronous Example
CommonJS (Sync):
const fs = require('fs');
const data = fs.readFileSync('file.txt', 'utf-8');
console.log(data);ESM (Async):
import { readFile } from 'fs/promises';
const data = await readFile('file.txt', 'utf-8');
console.log(data);What are module.exports, require, import, and export?
module.exports: An object used to define what should be exported from a CommonJS module.require: A function to import modules in CommonJS.export: Used in ES Modules to make parts of code available to other modules.import: Used in ES Modules to bring in exported values.
Node.js Module Types
1. Single File as Module
Each .js file is treated as a separate module:
// greet.js
module.exports = name => `Hi ${name}`;2. Folder as a Module
If a folder has an index.js, Node treats the folder as a module:
/my-module/index.js// index.js
module.exports = () => 'I am a folder module';const mod = require('./my-module');3. Grouping Files in Folder
Organize files in a folder and export from index:
// utils/add.js
module.exports = (a, b) => a + b;
// utils/subtract.js
module.exports = (a, b) => a - b;
// utils/index.js
module.exports = {
add: require('./add'),
subtract: require('./subtract'),
};Using Built-in util Module
const util = require('util');
const debugLog = util.debuglog('app');
debugLog('This will only log if NODE_DEBUG=app');
const promisify = util.promisify;
const sleep = promisify(setTimeout);
(async () => {
console.log('Waiting...');
await sleep(1000);
console.log('Done!');
})();⚠️ Note on ES Modules in Node.js
To use import/export in .js files, add this in package.json:
{
"type": "module"
}Summary
- Node.js supports both CommonJS and ES Modules.
- Use
module.exports/requirefor CommonJS, andexport/importfor ESM. CommonJSis synchronous;ESMis asynchronous.module.exportsis defaulted as an empty object that can be mutated or reassigned.- Node treats a single file, a folder with
index.js, or a group of files as modules. - The
utilmodule provides helper functions likepromisify,debuglog, etc.