The Wayback Machine - https://web.archive.org/web/20250110233941/https://www.geeksforgeeks.org/node-js-basics/
Open In App

Node.js Basics

Last Updated : 07 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Node.js is a powerful and efficient open-source runtime environment built on Chrome’s V8 JavaScript engine. It allows developers to run JavaScript on the server side, which helps in the creation of scalable and high-performance web applications.

Whether you are new to server-side programming or transitioning from front-end development, understanding the basics of Node.js is essential for building modern applications. This article will cover the fundamental concepts of Node.js, including its architecture, core modules, and how to get started with building your first application.

What is Node.js?

Node.js is a JavaScript runtime environment built on Chrome’s V8 JavaScript engine that allows developers to execute JavaScript code outside the browser. It can make console-based and web-based node.js applications.

Unlike traditional JavaScript environments, which are limited to the browser, Node.js gives developers the ability to run JavaScript on the server. It’s non-blocking and event-driven, which makes it ideal for building scalable applications, especially ones that require handling large numbers of simultaneous connections (like chat apps, streaming services, or real-time applications).

Key features of Node.js

  • Non-blocking I/O: Node.js is asynchronous, enabling efficient handling of concurrent requests.
  • Event-driven architecture: Developers can create event-driven applications using callbacks and event emitters.
  • Extensive module ecosystem: npm (Node Package Manager) provides access to thousands of reusable packages.
  • Single-threaded Model: Node js runs on a single thread despite being asynchronous, it uses an event loop to handle requests.

Node.js Architecture

Node.js follows a single-threaded event loop model that handles all client requests using a single thread. It is based on a non-blocking I/O model, meaning the server can process multiple requests without waiting for one task to complete before starting the next.

  1. Single-Threaded: Although Node.js runs on a single thread, it can handle thousands of concurrent requests using asynchronous callbacks.
  2. Event-Driven: The event-driven architecture allows Node.js to process multiple connections efficiently by triggering callbacks when an event occurs (e.g., receiving data, file I/O completion).
  3. Non-Blocking I/O: Instead of waiting for I/O operations (like reading from a file or querying a database) to complete, Node.js continues to execute the next line of code. The result is handled asynchronously, improving overall performance.

Setting Up Node.js

To start using Node.js, you’ll first need to install it on your system.

Step 1: Download and Install Node.js

  • Go to the Node.js official website or you can follow our article to install Node.js
  • Download the appropriate installer for your operating system (Windows, macOS, or Linux).
  • Follow the installation steps to set up Node.js.

Step 2: Verify Installation

Once installed, you can verify the installation by opening your terminal and typing the following commands:

node -v
npm -v

Core Modules

Node.js includes several core modules for essential functionality. Some commonly used ones are:

Datatypes in Node.js

Node.js contains various types of data types similar to JavaScript.

  • Boolean
  • Undefined
  • Null
  • String
  • Number

Loose Typing:

Node.js supports loose typing, which means you don’t need to specify what type of information will be stored in a variable in advance. We use the var and let keywords in Node.js declare any type of variable. Examples are given below: 

Example: This example demonstrates how the typeof operator in JavaScript dynamically checks and displays the data type of a variable after assigning different types of values to it.

JavaScript
// Variable store number data type
let a = 35;
console.log(typeof a);

// Variable store string data type
a = "GeeksforGeeks";
console.log(typeof a);

// Variable store Boolean data type
a = true;
console.log(typeof a);

// Variable store undefined (no value) data type
a = undefined;
console.log(typeof a);

Output
number
string
boolean
undefined

Objects and Functions:

Node.js objects are the same as JavaScript objects i.e. the objects are similar to variables and it contains many values which are written as name: value pairs. Name and value are separated by a colon and every pair is separated by a comma. 

Example: 

JavaScript
let company = {
    Name: "GeeksforGeeks",
    Address: "Noida",
    Contact: "+919876543210",
    Email: "abc@geeksforgeeks.org"
};

// Display the object information
console.log("Information of variable company:", company);

// Display the type of variable
console.log("Type of variable company:", typeof company);

Output
Information of variable company: {
  Name: 'GeeksforGeeks',
  Address: 'Noida',
  Contact: '+919876543210',
  Email: 'abc@geeksforgeeks.org'
}
Type of variable company: object

Functions in Node.js

Node.js functions are defined using the function keyword then the name of the function and parameters which are passed in the function. In Node.js, we don’t have to specify datatypes for the parameters and check the number of arguments received. Node.js functions follow every rule which is there while writing JavaScript functions. 

Example: 

javascript
function multiply(num1, num2) {

    // It returns the multiplication
    // of num1 and num2
    return num1 * num2;
}

// Declare variable
let x = 2;
let y = 3;

// Display the answer returned by
// multiply function
console.log("Multiplication of", x,
    "and", y, "is", multiply(x, y));

Output
Multiplication of 2 and 3 is 6

As you observe in the above example, we have created a function called “multiply” with parameters the same as JavaScript. 

String and String Functions in Node.js

In Node.js we can make a variable a string by assigning a value either by using single (”) or double (“”) quotes and it contains many functions to manipulate strings. Following is the example of defining string variables and functions in node.js.

Example: 

javascript
let x = "Welcome to GeeksforGeeks ";

let y = 'Node.js Tutorials';

let z = ['Geeks', 'for', 'Geeks'];

console.log(x);

console.log(y);

console.log("Concat Using (+) :", (x + y));

console.log("Concat Using Function :", (x.concat(y)));

console.log("Split string: ", x.split(' '));

console.log("Join string: ", z.join(', '));

console.log("Char At Index 5: ", x.charAt(5));


Output:

Welcome to GeeksforGeeks
Node.js Tutorials
Concat Using (+) : Welcome to GeeksforGeeks Node.js Tutorials
Concat Using Function : Welcome to GeeksforGeeks Node.js Tutorials
Split string: [ 'Welcome', 'to', 'GeeksforGeeks', '' ]
Join string: Geeks, for, Geeks
Char At Index 5: m

Buffer in Node.js

In node.js, we have a data type called “Buffer” to store binary data and it is useful when we are reading data from files or receiving packets over the network. 

JavaScript
let b = new Buffer(10000);//creates buffer
let str = " ";
b.write(str);
console.log(str.length);//Display the information
console.log(b.length); //Display the information


Output:

1
10000

Node.js console-based application

Make a file called console.js with the following code. 

JavaScript
console.log('Hello this is the console-based application');

console.log('This all will be printed in console');

// The above two lines will be printed in the console.

To run this file, open the node.js command prompt and go to the folder where the console.js file exists and write the following command. It will display content on console. The console.log() method of the console class prints the message passed in the method in the console. 

Node.js web-based application

Node.js web application contains different types of modules which is imported using require() directive and we have to create a server and write code for the read request and return response. Make a file web.js with the following code. 

Example:

JavaScript
// Require http module
let http = require("http");

// Create server
http.createServer(function (req, res) {

    // Send the HTTP header
    // HTTP Status: 200 : OK
    // Content Type: text/plain
    res.writeHead(200, { 'Content-Type': 'text/plain' });

    // Send the response body as "This is the example
    // of node.js web based application"
    res.end('This is the example of node.js web-based application \n');

    // Console will display the message
}).listen(5000,
    () => console.log('Server running at http://127.0.0.1:5000/'));


To run this file follow the steps as given below:

  • Search the node.js command prompt in the search bar and open the node.js command prompt.
  • Go to the folder using cd command in command prompt and write the following command node web.js
  • Now the server has started and go to the browser and open this url localhost:5000

You will see the response which you have sent back from web.js in the browser. If any changes are made in the web.js file then again run the command node web.js and refresh the tab in the browser.

Common Use Cases

  • Building RESTful APIs
  • Real-time applications using WebSockets
  • Microservices architecture
  • Serverless functions with AWS Lambda

Conclusion

Node.js is a versatile platform for building scalable and efficient apps with its event-driven, non-blocking architecture, making it perfect for real-time and I/O-heavy tasks. Though less suited for CPU-heavy work, its async model excels in modern app development. Dive deeper into its features and explore real-world use cases.

Node.js Basics – FAQ’s

How does Node.js handle asynchronous operations?

Node.js uses a non-blocking, event-driven architecture, where I/O operations are handled asynchronously using callbacks, promises, or async/await.

What is npm in Node.js?

npm (Node Package Manager) is the default package manager for Node.js, allowing developers to install, share, and manage JavaScript packages and dependencies

What is the Event Loop in Node.js?

The Event Loop is a mechanism in Node.js that allows it to handle asynchronous operations by offloading I/O tasks to the system while continuing to execute other code on a single thread.

How does Node.js handle errors?

Node.js uses the error-first callback pattern, where callbacks receive an error object as the first argument. Promises or try/catch blocks with async/await can also be used for error handling.


Become a Full-Stack Developer and also get 90% fee refund on completing 90% course in 90 days! Take the Three 90 Challenge today.

After successfully processing refunds worth over INR 5 Cr, GeeksforGeeks is back with the Three 90 challenge and this is your chance to upskill and get 90% refund. What more motivation do you need? Start the challenge right away!


Next Article

Similar Reads

three90RightbarBannerImg