Node Introduction

Node.js is an open-source, cross-platform runtime environment that allows you to run JavaScript on the server side. Unlike traditional JavaScript, which is typically executed in the browser, Node.js enables you to build scalable, high-performance applications outside the browser. It's built on Chrome's V8 JavaScript engine and is known for its non-blocking, event-driven architecture, making it ideal for real-time applications like chat apps, APIs, and data-intensive services.

 

Node.js is primarily asynchronous. This means that instead of waiting for a task to complete before moving on to the next one (which is how synchronous operations work), Node.js handles tasks concurrently.

It uses a non-blocking, event-driven architecture, allowing multiple operations to be processed at the same time.

For example, while waiting for a database query to return, Node.js can continue handling other requests, making it highly efficient for I/O-bound tasks. However, synchronous operations are also possible in Node.js, but they can block the event loop and are generally avoided in performance-critical applications.

Here are a few simple examples to illustrate synchronous and asynchronous behavior in Node.js:

1. Synchronous Example

const fs = require("fs");
const data = fs.readFileSync("read.txt", "utf-8"); //Reading a file synchronously
console.log("Data = ", data);
console.log("File reading completed");

Explanation:

In this example, fs.readFileSync reads the file synchronously, meaning the program waits until the file is fully read before moving on to the next line of code.

2. Asynchronous Example

fs.readFile("read.txt", "utf-8", (error, data) => {
  if (error) throw error;
  console.log(data);
});

console.log("Started reading the file...");

Explanation:

Here, fs.readFile reads the file asynchronously. The program doesn't wait for the file to be fully read before moving on to the next line. Instead, it continues with other tasks, and once the file reading is complete, the callback function is executed.

3. Asynchronous with a Timer

console.log("Start");

setTimeout(() => {
  console.log("Timeout finished");
}, 2000);

console.log("End");

Explanation:

In this example, setTimeout is an asynchronous function that schedules the callback to run after 2 seconds. The program doesn't pause for 2 seconds; it immediately moves on and logs "End," then logs "Timeout finished" after the delay.

4. Asynchronous with a Promise

const fetchData = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("Data fetched");
    }, 2000);
  });
};

console.log("Start");
fetchData().then((data) => {
  console.log(data);
});
console.log("End");

Explanation:

In this example, fetchData returns a Promise that resolves after 2 seconds. The program continues to execute "End" while waiting for the promise to resolve, demonstrating the asynchronous nature.