(lt.45) Beyond the Browser: Mastering Node.js for Real-Time & I/O-Bound Apps

(lt.45) Beyond the Browser: Mastering Node.js for Real-Time & I/O-Bound Apps

·

7 min read

Introduction

Node.js is a powerful, open-source, server-side runtime environment built on Google Chrome's V8 JavaScript engine. It enables developers to execute JavaScript code outside of a web browser
It uses an event-driven, non-blocking I/O model, and is cross-platform, meaning it can run on various operating systems like Windows, macOS, and Linux.

Node.js is single-threaded, meaning it can only execute one JavaScript task at a time, it achieves high concurrency through a different approach.

Applications of Node.js

  • Web Applications: Server-side rendering and APIs.

  • Real-time Applications: Chat applications, live streaming, online gaming.

  • Microservices: Building and managing distributed systems.

  • IoT Applications: Connecting and managing IoT devices.

  • API Services: GraphQL API development.

What is API

An API (Application Programming Interface) is a set of rules and protocols that allow different software applications to communicate with each other.

Types of APIs

  1. Web APIs: These are accessed over the internet using HTTP/HTTPS protocols. They are used to interact with web services, such as RESTful APIs, SOAP APIs, and GraphQL APIs.

    • RESTful APIs: Representational State Transfer APIs use standard HTTP methods like GET, POST, PUT, and DELETE.

    • SOAP APIs: Simple Object Access Protocol APIs use XML for message format and rely on protocols like HTTP, SMTP for message negotiation and transmission.

    • GraphQL APIs: Allow clients to request exactly the data they need, making queries more efficient and reducing the amount of data transferred.

  2. Library/Framework APIs: These are used to interact with libraries and frameworks within the same software. For example, the jQuery library has an API that provides a set of functions to manipulate the DOM.

  3. Operating System APIs: These allow applications to interact with the operating system. For example, the Windows API allows applications to interact with the Windows operating system

Architecture of NodeJS

Node.js is a programming language that utilizes both JavaScript an C/C++ to create its core components.

These components are:

  • Request Handling: The request is received and processed by the Node.js server.

  • Event Queue: If the request involves asynchronous operations (like reading a file or querying a database), these operations are initiated, and their callbacks are added to the event queue.

  • Event Loop: The event loop continuously checks the event queue and executes the callbacks when the corresponding asynchronous operations complete.

  • Thread Pool: If the asynchronous operation involves tasks that require the thread pool (like file system operations), the task is executed in one of the threads in the pool, and its callback is added to the event queue once completed.

  • Response: Once all necessary operations are completed, the server sends the response back to the client.

Important information:

The statement "blocking threads are non-blocking" is not entirely accurate. It's important to make a distinction between the nature of the operation and the execution model:

Nature of the operation: A blocking operation is one that suspends the execution of the current thread until it completes. This means that while the thread is waiting, it cannot execute any other code.

Execution model: Node.js utilizes a single-threaded event loop with a pool of worker threads. The event loop is responsible for handling non-blocking I/O and scheduling tasks. Worker threads are used to execute blocking operations asynchronously. Therefore, while an individual operation might be blocking, the execution model in Node.js utilizes worker threads and the event loop to manage these blocking operations in a non-blocking manner. This allows the main thread to remain responsive and handle other tasks while the blocking operations are running in the background. Node.js can handle blocking operations in a non-blocking way by utilizing worker threads and the event loop. This statement clarifies that the blocking nature of individual operations doesn't prevent Node.js from being a non-blocking environment overall.
Node.js internally decides whether a task will run on the main thread or a worker thread based on several factors.
Ultimately, Node.js aims to optimize performance and resource utilization by intelligently allocating tasks between the main thread and worker threads. While developers can influence this behavior through libraries, frameworks, and application architecture, the final decision ultimately rests with the Node.js runtime based on its internal analysis.

NPM

npm (Node Package Manager) is a package manager for JavaScript and the default package manager for the Node.js runtime environment. It helps developers to share and reuse code, as well as manage project dependencies. It is a command line utility
that makes it easy to install , share and manage packages of nodejs codes.

Key Features of npm

  1. Package Management: npm makes it easy to install, update, and manage JavaScript libraries and frameworks

  2. Dependency Management: npm handles the dependencies of your project by maintaining a package.json file, which lists all the packages and their versions required for the project. It ensures that the correct versions of dependencies are installed.

  3. Scripts: npm allows you to define custom scripts in the package.json file that can be run using the npm run command.

Key Components

  1. npm CLI (Command Line Interface): The npm CLI is the command-line tool used to interact with the npm ecosystem. It provides commands to install, update, and remove packages, among other tasks.

  2. npm Registry: The npm registry is a public database of JavaScript packages. Developers can publish their own packages to the registry, making them available for others to use.

  3. package.json: This is a configuration file that defines the metadata for a Node.js project, including its dependencies, version, author, scripts.

npm-init

The npm init command is used to initialize a new Node.js project by creating a package.json file, which contains metadata about the project and its dependencies. This file is essential for managing a project's dependencies and scripts.

Code

// for version check

PS D:\programing all things\js codes> npm -v
 9.6.7 

// make a new folder
mkdir React-app

// to fetch all the files of the react
npm init react-app path_name


// make a new folder
mkdir my-esm

// get inside this folder
cd my-esm

// installing esm libraries
npm init esm --yes
  • npm: The Node Package Manager, which is used to manage packages and dependencies in Node.js projects.

  • init: This initializes a new project.

  • esm: This specifies that the project will use the esm package for ECMAScript modules.

  • --yes: This flag skips the interactive questions and accepts default settings.

    Running npm init esm --yes sets up a new Node.js project with ECMAScript module support using the esm package, and it does so without asking any interactive setup questions by accepting the default settings automatically.

  •   // make new folder
      mkdir projects
    
      /// install package.json
      cd projects
      npm init -y
    
      // to install packages inside a package or to handle
      // more workspaces
       npm init -w packages/p1
    
      // to make a react project 
      npm init -w packages/my-react-app react-app my-react-app
    

Installing a package

For dev dependencies
search it by yourself and try to run for better understanding.

Uninstalling



{
  "name": "my-project",
  "version": "1.0.1",
  "description": "this is my project used to handle dependencies",
  "main": "index.js",
  "scripts": {
    "test": "npm run test"
  },
  "keywords": [
    "gopal",
    "project"
  ],
  "author": "gopal krishna",
  "license": "ISC",
  "dependencies": {
    "react": "^18.3.1"
  },
  "devDependencies": {
    "react-script": "^2.0.5"
  }
}

commands to demonstrate the above code

Basic Structure of package.json

jsonCopy code{
  "name": "my-project",              // The name of your project
  "version": "1.0.0",                // The current version of your project
  "description": "A sample project", // A brief description of your project
  "main": "index.js",                // The entry point file of your project
  "scripts": {                       // Custom scripts you can run with npm
    "start": "node -r esm index.js", // Command to start your project
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Your Name",             // The author of the project
  "license": "ISC",                  // The license for your project
  "dependencies": {                  // Dependencies required to run your project
    "esm": "^3.2.25"
  },
  "devDependencies": {               // Dependencies required only during development
    "mocha": "^8.3.2"
  },
  "keywords": [                      // Keywords to help others find your project
    "nodejs",
    "npm",
    "init"
  ],
  "repository": {                    // Information about the project's source code repository
    "type": "git",
    "url": "https://github.com/your-repo/my-project.git"
  }
}

Key Sections

  1. name: The name of your project.

  2. version: The version of your project, following semantic versioning (e.g., "1.0.0").

  3. description: A brief description of what your project does.

  4. main: The main entry point of your application (e.g., "index.js").

  5. scripts: Scripts to run various tasks in your project. Common scripts include:

    • start: Command to start your application.

    • test: Command to run your tests.

  6. author: The name of the project's author.

  7. license: The license under which the project is distributed.

  8. dependencies: Packages required for your project to run. These are installed with npm install.

  9. devDependencies: Packages required only for development, such as testing tools. These are also installed with npm install.

  10. keywords: An array of keywords to help people find your project.

  11. repository: Information about the source code repository for your project.

lt.44:https://hashnode.com/post/clyb9o3q500000al8b5qsbfj7

Did you find this article valuable?

Support himanshu by becoming a sponsor. Any amount is appreciated!