Basics of Node.js with Examples
Node.js has become one of the most popular tools for building modern web backends, APIs, real-time applications, and developer tools. If you already know some JavaScript and want to move to the server side, learning the basics of Node.js is a natural next step.
This beginner-friendly guide explains what Node.js is, why it is used, how its architecture works at a high level, and walks through core concepts like the runtime, modules, npm, and simple server examples so you can start building your first Node.js applications confidently.
What Is Node.js?
Node.js is an open-source, cross-platform JavaScript runtime environment that lets you run JavaScript code outside the browser, mainly on the server. It is built on Google’s V8 JavaScript engine (the same engine used in Chrome), which compiles JavaScript to fast machine code.
In simple terms, Node.js allows you to use JavaScript to build server-side applications: web servers, APIs, scripts, command-line tools, and even microservices. Instead of relying on PHP, Java, or Python on the backend, you can use the same language you use in the browser.
Key Features of Node.js
- Single-threaded, event-driven architecture for efficient handling of many connections.
- Non-blocking I/O so the server doesn’t wait while reading files or querying databases.
- Built-in module system to organize code and reuse functionality.
- Rich ecosystem via npm, the Node Package Manager, with hundreds of thousands of packages.
- Same language everywhere – JavaScript for both frontend and backend.
How Node.js Works (Simple View)
Unlike traditional servers that often use a thread for each request, Node.js uses a single main thread with an event loop. When a request comes in, Node.js quickly decides what to do and, for I/O tasks like reading from the disk or database, it delegates the work and continues to handle other requests.
When those background operations finish, callbacks or promises are used to handle the results. This event-driven, non-blocking design makes Node.js especially good for I/O-heavy applications such as APIs, real-time chat, streaming services, and dashboards.
Installing Node.js
To start using Node.js, download the installer from the official website and follow the installation wizard. Once installed, you can check the version in your terminal or command prompt:
node -v
npm -v
The node command runs JavaScript files with Node.js, and npm is the package manager used to install and manage third-party libraries.
Your First Node.js Program
The simplest Node.js program is a “Hello World” script in the terminal. Create a file called hello.js with the following content:
// hello.js
console.log('Hello from Node.js');Now run it from the terminal:
node hello.jsYou should see:
Hello from Node.js
This may look basic, but it proves the core idea: JavaScript can now run outside the browser, directly in your operating system.
Creating a Simple HTTP Server
One of the most common things you’ll do with Node.js is build web servers. Node.js has a built-in http module that makes this straightforward.
Here’s a simple HTTP server example:
// server.js
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello from a basic Node.js server!');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});Run the file with:
node server.js
Then open http://localhost:3000/ in your browser. You’ll see the “Hello from a basic Node.js server!” message served directly from your Node.js application.
Understanding CommonJS Modules
To keep code organized, Node.js uses a module system. Each file is a module, and you can export values from one file and import them into another. Older Node.js code uses CommonJS syntax (require and module.exports), which is still extremely common.
Creating and Using a Custom Module
Create a module file:
// mathUtils.js
function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
module.exports = {
add,
multiply
};Now use this module in another file:
// app.js
const math = require('./mathUtils');
const sum = math.add(5, 7);
const product = math.multiply(3, 4);
console.log('Sum:', sum);
console.log('Product:', product);
When you run node app.js, Node.js loads mathUtils.js, executes it once, and returns the exported object. This is the basis for structuring Node.js code into reusable modules.
Basics of npm (Node Package Manager)
npm is the default package manager for Node.js, and it hosts a huge number of reusable packages. Instead of writing everything from scratch, you can install existing libraries for routing, databases, authentication, logging, and more.
Initializing a Project
To start a Node.js project with npm, create a folder and run:
mkdir my-node-app
cd my-node-app
npm init -y
This creates a package.json file, which stores your project’s metadata and dependencies.
Installing a Package
For example, to install Express (a popular web framework for Node.js):
npm install express
This adds Express to your node_modules folder and saves the dependency in package.json, so others can install it by running npm install.
Building a Simple Express Server (Optional but Common)
While Node.js can handle HTTP directly, frameworks like Express make common tasks easier. Here’s a minimal Express example:
// index.js
const express = require('express');
const app = express();
// Middleware to parse JSON request bodies
app.use(express.json());
app.get('/', (req, res) => {
res.send('Hello from Express and Node.js');
});
app.post('/greet', (req, res) => {
const name = req.body.name || 'Guest';
res.json({ message: `Hello, ${name}!` });
});
app.listen(3000, () => {
console.log('Express server listening on http://localhost:3000');
});
This small app already shows routing (GET / and POST /greet), JSON handling, and a JSON response – common building blocks for REST APIs.
Core Built-in Modules in Node.js
Node.js ships with several built-in modules that help you interact with the operating system, file system, and network. Some important ones for beginners include:
- fs – File system (read, write, update files).
- path – Work with file and directory paths.
- http – Create HTTP servers and clients.
- os – Get operating system information.
- events – Work with event-driven patterns.
Example: Reading a File with fs
// readFileExample.js
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
return console.error('Error reading file:', err);
}
console.log('File contents:');
console.log(data);
});
The fs.readFile function is asynchronous and doesn’t block the main thread. When the file read finishes, the callback is executed with either an error or the data.
Example: Using the path Module
// pathExample.js
const path = require('path');
const fullPath = __filename;
const parsed = path.parse(fullPath);
console.log('Directory:', parsed.dir);
console.log('Base file name:', parsed.base);
console.log('Extension:', parsed.ext);
The path.parse method breaks a full file path into useful parts like directory, base name, and extension, which is very handy when dealing with file operations.
Event-Driven Programming in Node.js
Node.js is built around events. The events module allows you to create and listen for custom events, which is useful for decoupled and reactive code.
Simple Event Emitter Example
// eventsExample.js
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const emitter = new MyEmitter();
emitter.on('greet', (name) => {
console.log(`Hello, ${name}!`);
});
emitter.emit('greet', 'Node.js Developer');
Here, we define a custom event called greet and subscribe to it with a listener. When emitter.emit('greet', ...) is called, the listener runs. Many internal Node.js modules also use this pattern.
Blocking vs Non-Blocking Code
A very important Node.js basic is understanding the difference between blocking and non-blocking operations. Blocking code stops the event loop until the operation is finished, while non-blocking code lets other work continue in parallel.
Blocking Example (Not Recommended for Large Files)
// blockingExample.js
const fs = require('fs');
console.log('Reading file...');
const data = fs.readFileSync('largeFile.txt', 'utf8');
console.log('File length:', data.length);
console.log('Done.');
fs.readFileSync blocks the entire process until the file is read. If the file is large, other requests will have to wait.
Non-Blocking Example (Preferred)
// nonBlockingExample.js
const fs = require('fs');
console.log('Reading file...');
fs.readFile('largeFile.txt', 'utf8', (err, data) => {
if (err) return console.error(err);
console.log('File length:', data.length);
});
console.log('Done.');
In this version, the “Done.” message is printed immediately, and the file is read in the background. When Node.js finishes reading the file, it calls the callback, printing the file length. This is the non-blocking style you should prefer for scalability.
Common Use Cases for Node.js
- RESTful APIs – Quickly build JSON APIs for web and mobile apps.
- Real-time apps – Chat applications, notifications, live dashboards using WebSockets.
- Microservices – Small, independent services that communicate over HTTP or messaging.
- Developer tools – CLI tools, build systems, task runners.
- Streaming services – Handling audio/video streams or file streaming.
Best Practices for Beginners
- Use asynchronous (non-blocking) APIs by default to keep the application responsive.
- Organize code into modules instead of putting everything in a single file.
- Use
npm initandpackage.jsonto track dependencies and scripts. - Learn Promises and
async/awaitto write cleaner asynchronous code. - Handle errors properly in callbacks and promises to avoid crashes.
Conclusion
Node.js brings JavaScript to the server side with a powerful, event-driven, non-blocking architecture. By understanding the basics—how to run scripts, create simple servers, use modules, work with npm, and handle asynchronous operations—you already have the foundation needed to build real-world backends and tools.
From here, you can explore more advanced topics such as Express.js, databases (MongoDB, PostgreSQL, MySQL), authentication, testing, and production deployment. With consistent practice, Node.js can become one of your main tools for building fast, scalable, and modern web applications.

0 Comments