Node.js Basics - GeeksforGeeks (2024)

Last Updated : 06 May, 2024

Summarize

Comments

Improve

Node.js is a powerful runtime environment that allows developers to build server-side applications using JavaScript. In this comprehensive guide, we’ll learn all the fundamental concepts of Node.js, its architecture, and examples.

Table of Content

  • What is Node.js?
  • Key features of Node.js
  • Setting Up Node.js
  • Core Modules
  • Datatypes in Node.js
  • Node.js console-based application
  • Node.js web-based application
  • Common Use Cases
  • Conclusion

What is Node.js?

Node.js is an open-source, cross-platform JavaScript runtime built on Chrome’s V8 JavaScript engine. It allows the creation of scalable Web servers without threading and networking tools using JavaScript and a collection of “modules” that handle various core functionalities. It can make console-based and web-based node.js 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.

Setting Up Node.js

Before coming into Node.js development, ensure you have Node.js and npm installed. Visit the official Node.js website to download the latest version. Verify the installation using:

node -v

npm -v

Core Modules

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

  • fs(File System): Read/write files and directories.
  • http: Create HTTP servers and clients.
  • path: Manipulate file paths.
  • events: Implement custom event handling.

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:

javascript
// Variable store number data typelet a = 35;console.log(typeof a);// Variable store string data typea = "GeeksforGeeks";console.log(typeof a);// Variable store Boolean data typea = true;console.log(typeof a);// Variable store undefined (no value) data typea = undefined;console.log(typeof a);

Output

numberstringbooleanundefined

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: "[email protected]"};// Display the object informationconsole.log("Information of variable company:", company);// Display the type of variableconsole.log("Type of variable company:", typeof company);

Output

Information of variable company: { Name: 'GeeksforGeeks', Address: 'Noida', Contact: '+919876543210', Email: '[email protected]'}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 variablelet x = 2;let y = 3;// Display the answer returned by// multiply functionconsole.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 GeeksforGeeksNode.js TutorialsConcat Using (+) : Welcome to GeeksforGeeks Node.js TutorialsConcat Using Function : Welcome to GeeksforGeeks Node.js TutorialsSplit string: [ 'Welcome', 'to', 'GeeksforGeeks', '' ]Join string: Geeks, for, GeeksChar 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 bufferlet str = " ";b.write(str);console.log(str.length);//Display the informationconsole.log(b.length); //Display the information
110000

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. Node.js Basics - GeeksforGeeks (1) 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 modulelet http = require("http");// Create serverhttp.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 Node.js Basics - GeeksforGeeks (2)
  • Now the server has started and go to the browser and open this url localhost:5000 Node.js Basics - GeeksforGeeks (3)

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 applications. Dive deeper into its features and explore real-world use cases.



A

akshajjuneja9

Node.js Basics - GeeksforGeeks (4)

Improve

Previous Article

Installation of Node JS on Windows

Next Article

Node First Application

Please Login to comment...

Node.js Basics - GeeksforGeeks (2024)
Top Articles
What is self-directed investing?
What Is API Latency? | Postman Blog
Barstool Sports Gif
Truist Bank Near Here
Trevor Goodwin Obituary St Cloud
Weeminuche Smoke Signal
Room Background For Zepeto
Western Union Mexico Rate
Don Wallence Auto Sales Vehicles
Here are all the MTV VMA winners, even the awards they announced during the ads
Did 9Anime Rebrand
Kansas Craigslist Free Stuff
What happens if I deposit a bounced check?
Xm Tennis Channel
Alaska Bücher in der richtigen Reihenfolge
Johnston v. State, 2023 MT 20
Busted Newspaper S Randolph County Dirt The Press As Pawns
Espn Horse Racing Results
8664751911
Dark Chocolate Cherry Vegan Cinnamon Rolls
Walgreens San Pedro And Hildebrand
Talbots.dayforce.com
Welcome to GradeBook
Zoe Mintz Adam Duritz
Bjerrum difference plots - Big Chemical Encyclopedia
Xfinity Outage Map Fredericksburg Va
Urban Dictionary Fov
4 Times Rihanna Showed Solidarity for Social Movements Around the World
January 8 Jesus Calling
Walgreens On Bingle And Long Point
Leben in Japan – das muss man wissen - Lernen Sie Sprachen online bei italki
Biografie - Geertjan Lassche
Tracking every 2024 Trade Deadline deal
Publix Christmas Dinner 2022
Fastpitch Softball Pitching Tips for Beginners Part 1 | STACK
60 Second Burger Run Unblocked
Fridley Tsa Precheck
Green Bay Crime Reports Police Fire And Rescue
Tgh Imaging Powered By Tower Wesley Chapel Photos
Truckers Report Forums
Wildfangs Springfield
Viewfinder Mangabuddy
Kelley Blue Book Recalls
Is The Nun Based On a True Story?
Walmart Pharmacy Hours: What Time Does The Pharmacy Open and Close?
US-amerikanisches Fernsehen 2023 in Deutschland schauen
Thotsbook Com
Coffee County Tag Office Douglas Ga
116 Cubic Inches To Cc
Compete My Workforce
Varsity Competition Results 2022
Latest Posts
Article information

Author: Kieth Sipes

Last Updated:

Views: 6625

Rating: 4.7 / 5 (67 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Kieth Sipes

Birthday: 2001-04-14

Address: Suite 492 62479 Champlin Loop, South Catrice, MS 57271

Phone: +9663362133320

Job: District Sales Analyst

Hobby: Digital arts, Dance, Ghost hunting, Worldbuilding, Kayaking, Table tennis, 3D printing

Introduction: My name is Kieth Sipes, I am a zany, rich, courageous, powerful, faithful, jolly, excited person who loves writing and wants to share my knowledge and understanding with you.