- Node.js Tutorial
- NodeJS Home
- NodeJS Introduction
- NodeJS Setup
- NodeJS First App
- NodeJS REPL
- NodeJS Command Line
- NodeJS NPM
- NodeJS Callbacks
- NodeJS Events
- NodeJS Event-Loop
- NodeJS Event-Emitter
- NodeJS Global-Objects
- NodeJS Console
- NodeJS Process
- NodeJS Buffers
- NodeJS Streams
- Node.js File Handling
- Node.js File System
- Node.js Read/Write File
- Working with folders in Node.js
- HTTP and Networking
- Node.js HTTP Module
- Anatomy of an HTTP Transaction
- Node.js MongoDB
- MongoDB Get Started
- MongoDB Create Database
- MongoDB Create Collection
- MongoDB Insert
- MongoDB Find
- MongoDB Query
- MongoDB Sort
- MongoDB Delete
- MongoDB Update
- MongoDB Limit
- MongoDB Join
- Node.js MySQL
- MySQL Get Started
- MySQL Create Database
- MySQL Create Table
- MySQL Insert Into
- MySQL Select From
- MySQL Where
- MySQL Order By
- MySQL Delete
- MySQL Update
- MySQL Join
- Node.js Modules
- Node.js Modules
- Node.js Built-in Modules
- Node.js Utility Modules
- Node.js Web Module
- Node.js Advanced
- Node.js Debugger
- Node.js Scaling Application
- Node.js Packaging
- Node.js Express Framework
- Node.js RESTFul API
- Node.js Useful Resources
- Node.js Useful Resources
- Node.js Discussion
Node.js Built-In Modules
One of the strongest selling points of Node.js is its "batteries-included" philosophy. Node.js provides a rich set of built-in modules that offer core functionalities to build applications without needing external libraries. These modules are directly available within the runtime environment, meaning you don't have to run npm install to use them. This makes development faster, keeps your project dependencies lightweight, and ensures you are using code optimized specifically for the Node.js engine.
Key Features of Built-In Modules
- Standardized Functionality: Essential tasks like file handling, networking, and stream manipulation are handled through a consistent API.
- No Installation Required: Since these are part of the Node.js binary, they are always available, reducing "dependency hell."
- Optimized Performance: These modules are written in C++ and JavaScript, specifically tuned to work with the V8 engine and the libuv event loop.
- Minimal Setup: You simply use the
require()syntax (CommonJS) orimport(ES Modules) to bring them into your file.
node: prefix when importing built-in modules (e.g., require('node:fs')). This clarifies that the module is built-in and prevents conflicts with npm packages that might have the same name.
Commonly Used Built-In Modules
While Node.js has dozens of modules, these are the heavy hitters you will use in almost every project:
- fs (File System): Allows you to interact with the file system on your computer. This is essential for reading configuration files or logging data.
- http: The foundation of web development in Node.js. It allows you to create servers that listen for incoming network requests.
- path: Provides utilities for working with file and directory paths. This is vital for ensuring your code works on both Windows and Linux/macOS.
- os: Provides information about the user's operating system, such as available memory and CPU architecture.
- events: The core of Node's asynchronous architecture. Most built-in modules inherit from the
EventEmitterclass. - util: Provides helpful utility functions, such as converting callback-based functions into Promises.
Example Code
Using the fs Module
The File System module is critical for data persistence. In the example below, we use the "Sync" (Synchronous) version for simplicity, though asynchronous versions are preferred for web servers.
const fs = require('node:fs');
// Writing to a file (creates the file if it doesn't exist)
fs.writeFileSync('config.log', 'Log Entry: System Started');
console.log('File written successfully.');
// Reading from a file
// 'utf8' is the encoding; without it, you'll get a raw Buffer (binary data)
const data = fs.readFileSync('config.log', 'utf8');
console.log('File content:', data);
fs.readFileSync blocks the entire Node.js event loop until the file is read. In a high-traffic web server, this will freeze the application for all users. For production apps, always use the asynchronous fs.promises API.
Using the http Module
This module allows Node.js to transfer data over the HyperText Transfer Protocol (HTTP). Even if you use a framework like Express.js later, it is built on top of this http module.
const http = require('node:http');
// Create an HTTP server
const server = http.createServer((req, res) => {
// 'req' represents the incoming request; 'res' is the response we send back
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ message: 'Hello from the native Node server!' }));
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
res.end(). If you don't end the response, the browser will keep spinning indefinitely, waiting for the server to finish.
Using the path Module
Working with file paths manually is risky because Windows uses backslashes (\) while Linux and macOS use forward slashes (/). The path module handles this for you automatically.
const path = require('node:path');
// Join paths safely based on the current Operating System
const uploadFolder = path.join(__dirname, 'public', 'uploads', 'images');
console.log('Target Upload Path:', uploadFolder);
// Get specific details about a file path
const fileInfo = path.parse('/users/admin/project/index.html');
console.log('File Name:', fileInfo.base); // index.html
console.log('Extension:', fileInfo.ext); // .html
Using the os Module
The os module is great for system monitoring or building "health check" endpoints for your applications.
const os = require('node:os');
const totalRamGB = (os.totalmem() / 1024 / 1024 / 1024).toFixed(2);
const freeRamGB = (os.freemem() / 1024 / 1024 / 1024).toFixed(2);
console.log(`System Platform: ${os.platform()}`);
console.log(`Total RAM: ${totalRamGB} GB`);
console.log(`Available RAM: ${freeRamGB} GB`);
os.cpus().length to determine how many CPU cores are available. This is a common practice when setting up the Node.js Cluster module to run multiple instances of your app to handle more traffic.
Summary
Node.js built-in modules provide the essential tools required to build professional-grade applications. By mastering modules like fs for file management, http for networking, and path for cross-platform compatibility, you reduce your reliance on third-party packages and write more efficient code. While external libraries have their place, starting with these native tools is the best way to understand the true power and performance of the Node.js runtime.