WikiGalaxy

Personalize

What is Node.js?

Overview:

Node.js is an open-source, cross-platform JavaScript runtime environment that allows developers to execute JavaScript code outside of a web browser. It is primarily used for building scalable network applications.

Key Features:

  • Event-driven architecture
  • Non-blocking I/O model
  • Single-threaded but highly scalable
  • Rich ecosystem with npm (Node Package Manager)

Use Cases:

  • Web servers and APIs
  • Real-time applications like chat apps
  • Microservices architecture
  • Server-side scripting

Event-driven Architecture

Concept:

Node.js operates on an event-driven architecture, meaning it uses events to trigger actions instead of traditional request/response models. This allows for handling multiple connections efficiently.


const EventEmitter = require('events');
const eventEmitter = new EventEmitter();

eventEmitter.on('start', () => {
  console.log('Event started');
});

eventEmitter.emit('start');
        

Explanation:

This example demonstrates creating an event emitter in Node.js. The 'start' event is defined and triggered, executing the associated callback function.

Console Output:

Event started

Non-blocking I/O Model

Concept:

Node.js uses a non-blocking I/O model which allows it to handle multiple operations simultaneously without waiting for any function to complete.


const fs = require('fs');

fs.readFile('file.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

console.log('Reading file...');
        

Explanation:

This code reads a file asynchronously, allowing the 'Reading file...' message to be logged before the file content is printed, demonstrating non-blocking behavior.

Console Output:

Reading file...

[File Content]

Single-threaded but Highly Scalable

Concept:

Node.js is single-threaded, using the event loop to handle concurrent operations, making it highly scalable for handling numerous connections.


const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello World\n');
});

server.listen(3000, '127.0.0.1');
console.log('Server running at http://127.0.0.1:3000/');
        

Explanation:

This example sets up a basic HTTP server using Node.js. Despite being single-threaded, it can handle multiple requests efficiently through the event loop.

Console Output:

Server running at http://127.0.0.1:3000/

Rich Ecosystem with npm

Concept:

Node.js has a rich ecosystem facilitated by npm, the Node Package Manager, which provides access to thousands of libraries and tools to enhance application development.


const _ = require('lodash');
const numbers = [1, 2, 3, 4, 5];

console.log(_.shuffle(numbers));
        

Explanation:

The lodash library, installed via npm, provides utility functions for common programming tasks. This example uses lodash to shuffle an array of numbers.

Console Output:

[Shuffled Numbers]

Web Servers and APIs

Concept:

Node.js is widely used for creating web servers and RESTful APIs due to its non-blocking nature and scalability.


const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello World');
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});
        

Explanation:

This example uses Express, a popular Node.js framework, to set up a simple web server that responds with 'Hello World' to GET requests at the root URL.

Console Output:

Server is running on port 3000

Real-time Applications

Concept:

Node.js is ideal for real-time applications, such as chat applications, due to its event-driven, non-blocking architecture.


const http = require('http');
const socketio = require('socket.io');

const server = http.createServer((req, res) => {
  res.end('Real-time Server');
});

const io = socketio(server);

io.on('connection', (socket) => {
  console.log('New client connected');
  socket.on('message', (msg) => {
    console.log('Message received: ', msg);
  });
});

server.listen(3000, () => {
  console.log('Real-time server running on port 3000');
});
        

Explanation:

This example sets up a real-time server using Socket.io, which facilitates WebSocket communication for real-time, bidirectional communication between clients and servers.

Console Output:

Real-time server running on port 3000

Microservices Architecture

Concept:

Node.js is often used in microservices architecture due to its lightweight and fast nature, making it suitable for building independent and small services that communicate over a network.


const express = require('express');
const app = express();

app.get('/service', (req, res) => {
  res.send({ message: 'This is a microservice' });
});

app.listen(4000, () => {
  console.log('Microservice running on port 4000');
});
        

Explanation:

This example demonstrates a simple microservice using Express. It listens on port 4000 and responds with a JSON message, showcasing how Node.js can be used to build microservices.

Console Output:

Microservice running on port 4000

Server-side Scripting

Concept:

Node.js is used for server-side scripting, where JavaScript is used to write scripts that run on the server-side to produce dynamic web page content before the page is sent to the user's web browser.


const http = require('http');

http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/html' });
  res.end('

Hello, this is server-side scripting!

'); }).listen(5000, () => { console.log('Server-side script running on port 5000'); });

Explanation:

This example creates a server that sends an HTML response to the client, demonstrating how Node.js can be used for server-side scripting to deliver dynamic content.

Console Output:

Server-side script running on port 5000

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025