Back to all posts

Node JS Core Concepts


Node.js is an open-source, cross-platform runtime envionment built on the V8 JavaScript engine from Google Chrome. It enables the execution of JavaScript on the server side, allowing for full-stack development using a single language.

Node.js employs a non-blocking, event-driven architecture, which makes it efficient for handing multiple simultaneous connection. It operates on a single-threaded event loop that manages asynchronous operation without creating new threads for each request.


Core Concepts

  • Modules: Node.js application are structured using modules, which are reusable blocks of code. There are three types of modules:
    • Core Modules: Built into Node.js (eg: fs, http, os).
    • Local Modules: Custom modules created by developers.
    • Third-party Module: Modules installed via npm (Node Package Manager) from the community
  • Event Loop: The event loop is central to Node.js’s non-blocking I/O model. It allow the execution of asynchronous operations by placing them in a queue and processing them as resources become available.
  • Streams: Streams in Node.js enable efficient data processing by handing data piece-by-piece rather than loading everything into memory at once. This is particularly usefull for large datasets or real-time data processing.

1. Core Node.js Modules

Node.js includes a set of core modules that provide essential functionalities for building applications. These modules are pre-installed with Node.js and can be imported using the require() function.

Examples of Core Modules

  • http: Used to create HTTP servers.
  • fs: Provides file system operations (e.g., reading/writing files).
  • path: Handles file paths.
  • url: Parses and resolves URLs.
  • querystring: Handles query string parsing.
  • os: Provides information about the operating system.
  • events: Implements an event-driven architecture.

const http = require(‘http’); // Importing the HTTP core module


2. Creating a Node.js Server

Node.js allows you to create a server using the http module. The server listens for incoming requests and sends responses.

const http = require('http');

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello, Node.js!');
});

server.listen(3000, '127.0.0.1', () => {
    console.log('Server is running at http://127.0.0.1:3000/');
});
  • The server listens on port 3000.
  • Use res.end() to send a response.

3. Node.js Program Lifecycle & Event Loop

Lifecycle

  • A Node.js program runs until there is no more work to do (e.g., no pending timers or callbacks).
  • The program exits automatically when all tasks are complete.

Event Loop

  • Node.js uses a single-threaded, non-blocking event loop to handle multiple requests efficiently.
  • The event loop processes asynchronous operations (e.g., I/O tasks) in phases:
    1. Timers (e.g., setTimeout)
    2. Pending callbacks
    3. Polling for I/O events
    4. Closing callbacks

4. Asynchronous Code in Node.js

Key Features

  • JavaScript in Node.js is non-blocking by default.
  • Asynchronous operations are handled using:
    • Callbacks
    • Promises (thencatch)
    • Async/Await syntax

Example Using Callbacks

const fs = require('fs');

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

Example Using Promises

const fs = require('fs/promises');

async function readFile() {
    try {
        const data = await fs.readFile('example.txt', 'utf8');
        console.log(data);
    } catch (err) {
        console.error(err);
    }
}

readFile();

5. Request & Response Handling

Request Parsing

Node.js processes incoming request data in chunks using streams and buffers to handle large payloads efficiently.

Avoiding Double Responses

Ensure that the response is sent only once to avoid errors:

if (!res.headersSent) {
    res.end('Response sent!');
}

6. The Node.js Module System

Types of Modules

  1. Core Modules: Built into Node.js (e.g., httpfspath)
  2. Local Modules: Custom modules created by developers.
  3. Third-party Modules: Installed via npm (e.g., expresslodash)

Importing Modules

  • Use require() for importing:
const fs = require('fs'); // Core module
const myModule = require('./myModule'); // Local module

Exporting Modules

  • Export single or multiple items:
// Exporting a single item
module.exports = function greet() {
    console.log('Hello!');
};

// Exporting multiple items
module.exports = {
    greet,
    farewell() {
        console.log('Goodbye!');
    }
};

By understanding these foundational concepts of Node.js, we can build scalable and efficient applications while leveraging its asynchronous and modular architecture effectively!