03-NodeJS Explained: How It Works and Reasons to Use It

Darshan BagadeDarshan Bagade
4 min read

Node.js is an event-driven JavaScript runtime that allows JavaScript to run independently on a server, which was previously only possible within a browser. This capability makes Node.js suitable for large-scale professional projects due to its easy scalability and non-blocking (asynchronous) nature. It boasts a large ecosystem with extensive community support, and even NASA uses Node.js for satellites.

Introduction

Node.js has revolutionized the way JavaScript is used in web development. Initially confined to browsers, JavaScript can now run on servers, thanks to Node.js. This shift has opened up new possibilities for building scalable and efficient applications.

Synchronous

  • Program executes line by line, meaning the next line of code will execute only when the previous line of code is executed.

  • The next task will not execute until the previous task is completed.

  • Blocking behavior: In blocking behavior, each operation must complete before the next one starts, meaning the program waits for a task to finish before moving on to the next.

  • Takes too much time to perform operations.

Asynchronous

  • Asynchronous programming allows Node.js to handle multiple operations without waiting for any of them to complete. This is achieved through non-blocking I/O operations.

  • It starts to execute the code and continues. It doesn't wait for any task to be completed; it continues the execution of the next task. The previous task will give the result whenever it is completed.

  • ex : setTimeout()

JavaScript is inherently synchronous, meaning it executes code line by line, waiting for each operation to complete before moving on to the next. However, Node.js introduces asynchronous behavior through non-blocking(does not wait for an operation) I/O operations, allowing it to handle multiple tasks concurrently without waiting for each to finish. This makes Node.js highly efficient for I/O-bound tasks.

Node REPL

  • READ-EVALUATE-PRINT-LOOP

  • Enter node in terminal to enter in the node REPL

  • .help for accessing the more commands

  • .break Sometimes you get stuck, this gets you out

  • .clear Alias for .break

  • .editor Enter editor mode

  • .exit Exit the REPL

  • .help Print this help message

  • .load Load JS from a file into the REPL session`

  • .save Save all evaluated commands in this REPL session to a file

  • Press Ctrl+C to abort current expression, Ctrl+D to exit the REPL

npm packages

A package is a collection of modules that includes a package.json file.

  • Node Package Manager

  • Open source with numerous community-contributed packages.

  • Create and publish your own packages.

  • Vast ecosystem of libraries and tools.

  • Initialize a project: npm init

  • Manages project dependencies and scripts via package.json

  • add "type" :"module" when import is use to include the module

  • Install, update, and uninstall packages

  • npm install <something> or npm i <package> (local) : to install the package

  • set/add : "type" : "module". By default it is commonjs into package.json

  • NPM Packages

  • npm init -y

Node Modules

A module is an individual file inside a package that exports functionality.

  • Predefined modules which we can access in our code

  • Modules can be core modules, local modules, or third-party modules

  • Core modules are built into Node.js and can be used without any additional installation

  • Local modules are created locally in your Node.js application

  • Third-party modules are installed from the npm registry

  • Modules help in organizing code into reusable components

  • Commonly used core modules include fs, http, path, and os

  • Modules are imported using the require function.

  • Example: const fs = require('fs');

  • Example : import mongoose from "mongoose"; (Commoly used)

  • Modules can export functions, objects, or values using module.exports

  • Example: module.exports = function() { /* function code */ };

  • Node Modules

import Statement

  • The import statement is part of the ES6 (ECMAScript 2015) module system. It is used to import bindings that are exported by another module. This syntax is more modern and is commonly used in newer JavaScript projects.

  • when we use import , we have to mention the "type" : "module" in package.json

Example:

import inquirer from 'inquirer';
import qr from 'qr-image';
import fs from 'fs';

.require Function

  • The require function is part of the CommonJS module system, which has been traditionally used in Node.js. It is used to include modules, JSON, and local files.

  • when we use require function, we have to mention the "type" : "commonjs" in package.json

Example:

const inquirer = require('inquirer');
const qr = require('qr-image');
const fs = require('fs');

Key Difference Between Module and Package

FeatureModulePackage
DefinitionA single JavaScript file that exports functions or variablesA collection of modules with package.json
Exampleqr.js file inside qr-imageqr-image package itself
InstallationJust a JavaScript fileInstalled via npm install qr-image

.env

The .env file is used to store environment variables for your application. These variables can include sensitive information like API keys, database credentials, or configuration settings. By keeping these variables in a separate file, you can easily manage and change them without modifying your code. This also helps keep sensitive information secure and out of your source code.

Any questions related to the topic above will be clarified in future articles.

Conclusion

Node.js offers a powerful platform for building scalable and efficient applications. Its asynchronous nature and extensive ecosystem make it a popular choice for developers worldwide. Whether you're working on a small project or a large-scale application, Node.js provides the tools and flexibility needed to succeed.

0
Subscribe to my newsletter

Read articles from Darshan Bagade directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Darshan Bagade
Darshan Bagade