Node.js is a JavaScript runtime built on Chrome’s V8 engine that enables server-side development. Its core modules are built-in libraries that provide essential features for building efficient and scalable applications.
- Pre-installed modules (no external installation needed)
- Improve performance and application scalability
- Common examples: fs, http, path
To use a core module, you simply use the require() function:
const fs= require('fs');List of Commonly Used Node.js Core Modules
A collection of built-in Node.js modules that provide essential functionalities like file handling, networking, and system operations without requiring installation
1. fs (File System)
The fs (File System) module in Node.js is a built-in module used to interact with the file system. It supports both synchronous and asynchronous operations for handling files and directories efficiently.
- Used to create, read, update, delete, and rename files/directories.
- Supports synchronous and asynchronous (non-blocking) operations.
- fs.readFile() reads file content asynchronously.
- Using 'utf-8' encoding returns data as a readable string.
- Returns an error if reading fails; otherwise, displays file content in the console.
const fs = require('fs');
fs.readFile('Lucas.txt', 'utf8', (err, data) => {
if (err) {
throw err;
}
console.log(data);
});
Lucas, You have Created file system successfully
Node is used to execute the fs.js script. When the script runs, it uses the fs module to read the Lucas.txt file and prints the message:
Output:

Note: When running a file using Node.js, it does not automatically watch for changes. If you make any changes to the file, you need to manually stop and restart the application for the updates to take effect.
fs module in Node.js provides methods for interacting with the file system are as follows:
- For Reading Files: fs.readFile/ fs.readFileSync
- For Writing Files: fs.writeFile/fs.writeFileSync
- For appending Files: fs.appendFile/ fs.appendFileSync
- For deleting Files: fs.unlink/ fs.unlinkSync and fs.rm/fs.rmSync
fs.appendfile: fs.appendFile() adds data to a file. It takes the file name, data, and a callback with err and throws an error if it fails, otherwise prints a success message.
filename: fs.js
const fs= require('fs');
fs.appendFile('Lucas.txt', 'file added successfully',(err)=>{
if(err)throw error;
console.log('Data added in my file Successfully');
})
Output:

fs.appendfileSync: It is synchronous method from Node.js built-in module. It is used to append data to file. If the specified file will not be created fileappendSync will automatically create it.
filename: fsappendSync.js
const fs=require('fs');
fs.appendFileSync('Lucas.txt', 'file added Successfully')
console.log('data added in file successfully');
Output:

Difference Between readFile/writeFile and readFileSync/writeFileSync
readFile/ writeFile | readFileSync/writeFileSync |
|---|---|
Asynchronous (non-blocking) | Synchronous (blocking) |
Better for high-performance and large-scale applications | Slower, blocks the event loop until the operation completes |
Takes a callback function | Returns result directly or throws error |
Preferred in server environments to avoid blocking | Useful for small scripts or startup code |
Error passed to callback | Use try...catch block for error handling |
fs.readFile('file.txt', 'utf8', (err, data) => {...}) | const data = fs.readFileSync('file.txt', 'utf8') |
fs.writeFile('file.txt', data, err => {...}) | fs.writeFileSync('file.txt', data) |
2. http and https(HTTP/HTTPS)
The http and https modules in Node.js are built-in modules used to create HTTP and HTTPS servers and handle web requests securely. They allow developers to build web servers, RESTful APIs, and interact with web services.
- Imported using require('http').
- http.createServer() creates a server with req and res objects.
- Sends response: "Hello Lucas, this is your first http server".
- Server listens on port 8080.
- Logs: "Lucas, your server is running on port 8080" when started.
filename: http.js
const http = require('http');
const myServer = http.createServer((req, res) => {
res.end('Hello Lucas, this is your first HTTP server');
});
myServer.listen(8080, () => {
console.log('Lucas, your server is running on port 8080');
});
This result of running the Node.js server using node, which will start your server on provided port no.

Finally, the message "Lucas, your server is running on port 8080" appears, indicating that the server started successfully and is now live.
Output:

- When accessed in the browser at http://localhost:8080, it displays the message "Hello Lucas, this is your first http server", confirming the server works correctly.
- The https module creates secure servers using SSL/TLS encryption and is similar to the http module.
- Used for secure communication and handling sensitive data like login details or payments.
filename: https.js
const https = require("https");
const { readFile } = require("fs/promises");
const path = require("path");
const fs = require("fs");
const mimetypes = {
html: "text/html",
css: "text/css",
js: "application/javascript"
};
const options = {
pfx: fs.readFileSync(path.join(__dirname, "ssl/cert.pfx")),
passphrase: process.env.SSL_PASSPHRASE
};
https.createServer(options, async (req, res) => {
try {
let filePath = req.url === "/" ? "homepage.html" : req.url;
const safePath = path.normalize(path.join(__dirname, filePath));
if (!safePath.startsWith(__dirname)) {
res.writeHead(403);
return res.end("Forbidden");
}
const content = await readFile(safePath);
const ext = path.extname(filePath).slice(1);
res.writeHead(200, {
"Content-Type": mimetypes[ext] || "text/plain"
});
res.end(content);
} catch (err) {
res.writeHead(404);
res.end("File Not Found");
}
}).listen(8080, () => {
console.log("HTTPS Server running on https://localhost:8080");
});
Note: Whatever the port number and IP Address are given to the server.listen it will execute that only web page whenever requested. And this web page will be HTTPS.
3. events(EventEmitter)
Node.js follows an event-driven architecture, and the events module plays a central role in it. It provides the EventEmitter class to create and handle custom events asynchronously.
- Enables creation and handling of custom events.
- Forms the foundation for real-time and event-based applications.
filename: EventEmitter.js
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('Message', (msg) => {
console.log(`Received: ${msg}`);
});
myEmitter.emit('Message', 'Hello Lucas');
- Imports the EventEmitter class from the events module and creates an instance myEmitter.
- Uses myEmitter.on() to listen for a 'Message' event and execute a callback function.
- Triggers the event using myEmitter.emit() and prints "Hello Lucas" to the console.
Output:

- Node successfully executed the eventemitter.js file.
- The script emitted a custom 'Message' event using emit().
- A listener registered with on() handled the event.
- The message "Hello Lucas" was printed to the console, confirming the event emitter worked correctly.
4. path(Path)
The path module simplifies working with file and directory paths. It offers functions like join, resolve, and basename to manipulate and construct paths in a platform-independent way.
filename : path.js
const path = require('path');
console.log(path.basename('C:\\Users\\GFG0925-LAPTOP\\Desktop\\gfg_code\\NodeJS\\index.html'));
Output:

- The path.js file was executed using Node.js.
- It printed index.html to the console.
- This indicates that path.basename() was used to extract the file name from a full file path.
5. util(Utilities)
The util module contains utility functions that extend JavaScript's built-in capabilities. It's particularly useful for debugging and working with objects. You'll find functions like promisify, inspect, and format here.
filename:util.js
const util =require('util');
const text=util.format('Hello %s', 'Lucas');
console.log(text);
It uses Node.js’s built-in util module, specifically the util.format() method, to format a string. The %s is a placeholder for a string value, which gets replaced by "Lucas" in this case. The result is a formatted string: "Hello Lucas".
Output:

- The util.js script ran successfully using nodemon.
- The output "Hello Lucas" was printed to the console.
- This confirms that util.format('Hello %s', 'Lucas') correctly replaced %s with 'Lucas'.
6. os (Operating System)
The os module provides information about the operating system on which Node.js is running. You can access details like CPU architecture, memory, and network interfaces. It's essential for writing platform-specific code.
filename: os.js
const os=require('os');
console.log(os.platform());
console.log(os.freemem());
console.log(os.arch());
This Node.js code uses the built-in os module to get information about the operating system. It prints the platform (like 'linux' or 'win32'), the system architecture (like 'x64'), and the amount of free system memory (in bytes).
Output:

- The os.js script uses Node.js’s built-in os module to get system information.
- It displays the platform (os.platform()), architecture (os.arch()), and free memory (os.freemem()).
- Helps identify the system environment where the Node.js application is running.
7. crypto(Cryptography)
For handling cryptographic operations like encryption, decryption, and creating hashes, the crypto module is indispensable. It includes functions for secure data handling and authentication.
filename: crypto.js
const crypto= require('crypto');
const hash= crypto.createHash('sha256');
const result= hash.update('Hello, Mahima Bhardwaj').digest('hex');
console.log(result);
- Uses the built-in crypto module to generate a SHA-256 hash.
- Creates a hash with crypto.createHash('sha256') and updates it with the string "Hello, Lucas".
- Converts the hash to hexadecimal using digest('hex') and prints the result to the console.
Output:

- Successfully generated a SHA-256 hash of the string "Hello, Lucas".
- The hashed output is displayed in hexadecimal format.
- Nodemon is now waiting for file changes to automatically restart the script.
Usage of Core Modules
To use a core module, you need to require it in your Node.js script:
filename: coremodule.js
const fs =require('fs');
const path= require('path');
const http= require('http');
const util=require('util);')
Once required, you can access the module’s functions and classes and start using them in your application.
An example of reading a file using the fs module:
const fs = require('fs');
fs.readFile('Lucas.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log('File content:', data);
});