Node.js has rapidly gained popularity as a powerful environment for building server-side applications. Its non-blocking, event-driven architecture makes it ideal for I/O-bound tasks, real-time applications, and microservices. If you’re a beginner eager to learn Node.js, this article will guide you through some simple examples that will elevate your skills from zero to hero!

Getting Started with Node.js

Before diving into code, you need to set up your development environment. Follow these steps:

  1. Install Node.js: Download Node.js from nodejs.org and follow the installation instructions for your operating system.
  2. Create a New Directory: For this example, create a new directory for your Node.js projects.
    mkdir nodejs-beginners
    cd nodejs-beginners
  3. Initialize a New Node Project: Initialize a new Node.js project using npm (Node Package Manager).
    npm init -y

Once you have your environment set up, you can start creating simple applications with Node.js.

Example 1: “Hello World” Server

One of the first things you can do with Node.js is create a basic web server.

Code:

const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});

Explanation:

  • You require the built-in http module.
  • A server is created that listens for incoming requests.
  • When a request is received, it returns a plain text response of “Hello World”.
  • Start your server using node yourfile.js and visit http://127.0.0.1:3000 in your browser.

Example 2: Basic REST API

Let’s create a simple REST API for managing a list of items.

Code:

const http = require('http');
let items = ['Item 1', 'Item 2', 'Item 3'];
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'application/json');
if (req.method === 'GET') {
res.statusCode = 200;
res.end(JSON.stringify(items));
} else if (req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
items.push(body);
res.statusCode = 201;
res.end(JSON.stringify({ message: 'Item added' }));
});
} else {
res.statusCode = 405; // Method Not Allowed
res.end(JSON.stringify({ error: 'Method Not Allowed' }));
}
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});

Explanation:

  • This server manages an array of items.
  • It handles GET requests by returning the current list of items.
  • For POST requests, it collects and adds a new item to the list.
  • Use a tool like Postman or cURL to test the POST functionality.

Example 3: Using Express.js for Simplicity

While the examples above use Node.js’s built-in modules, you can simplify your server code by using Express.js, a minimalistic framework.

Code:

First, install Express:

npm install express

Now create a simple Express server.

const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());
let items = ['Item 1', 'Item 2', 'Item 3'];
app.get('/items', (req, res) => {
res.json(items);
});
app.post('/items', (req, res) => {
items.push(req.body.item);
res.status(201).json({ message: 'Item added' });
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});

Explanation:

  • Express simplifies routing and handling JSON requests.
  • The app defines two routes for getting and posting items.
  • Testing this API can also be done via Postman or equivalent tools.

Example 4: Reading Files

Node.js excels at handling filesystem operations asynchronously, making tasks like reading files simple.

Code:

const fs = require('fs');
fs.readFile('sample.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading the file:', err);
return;
}
console.log('File content:', data);
});

Explanation:

  • Using the fs module, you can read a text file asynchronously.
  • If successful, it logs the file contents; otherwise, it logs the error.

Conclusion

By exploring these simple Node.js examples, you have laid the foundation to build more complex applications. From creating a basic web server to managing APIs and reading files, these skills will serve as stepping stones to mastering Node.js. Keep experimenting and building, as practice is key to becoming proficient in any programming language. Happy coding!

Top 5 Node.js Examples to Kickstart Your Next Project
Creating a Real-Time Chat Application with Node.js: An In-Depth Guide

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.