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
How to Sell Books on Amazon: Complete Guide for 2024
How To Make Money On Kindle Without Writing
Directions To Franklin Mills Mall
Unblocked Games Premium Worlds Hardest Game
Alan Miller Jewelers Oregon Ohio
St Petersburg Craigslist Pets
P2P4U Net Soccer
O'reilly's In Monroe Georgia
Noaa Swell Forecast
Crazybowie_15 tit*
Snarky Tea Net Worth 2022
Bme Flowchart Psu
Tight Tiny Teen Scouts 5
World History Kazwire
Whitefish Bay Calendar
Craigslist List Albuquerque: Your Ultimate Guide to Buying, Selling, and Finding Everything - First Republic Craigslist
Teacup Yorkie For Sale Up To $400 In South Carolina
Kringloopwinkel Second Sale Roosendaal - Leemstraat 4e
Dragonvale Valor Dragon
Company History - Horizon NJ Health
Del Amo Fashion Center Map
Jeff Nippard Push Pull Program Pdf
Chamberlain College of Nursing | Tuition & Acceptance Rates 2024
Bra Size Calculator & Conversion Chart: Measure Bust & Convert Sizes
Keshi with Mac Ayres and Starfall (Rescheduled from 11/1/2024) (POSTPONED) Tickets Thu, Nov 1, 2029 8:00 pm at Pechanga Arena - San Diego in San Diego, CA
Visit the UK as a Standard Visitor
Mumu Player Pokemon Go
Metro By T Mobile Sign In
Human Unitec International Inc (HMNU) Stock Price History Chart & Technical Analysis Graph - TipRanks.com
Forager How-to Get Archaeology Items - Dino Egg, Anchor, Fossil, Frozen Relic, Frozen Squid, Kapala, Lava Eel, and More!
What Time Is First Light Tomorrow Morning
October 31St Weather
Pitchfork's Top 200 of the 2010s: 50-1 (clips)
Dying Light Nexus
Wisconsin Women's Volleyball Team Leaked Pictures
Ktbs Payroll Login
Dr Adj Redist Cadv Prin Amex Charge
craigslist: modesto jobs, apartments, for sale, services, community, and events
Craigslist Freeport Illinois
Great Clips Virginia Center Commons
Winta Zesu Net Worth
Citibank Branch Locations In North Carolina
Brake Pads - The Best Front and Rear Brake Pads for Cars, Trucks & SUVs | AutoZone
Lady Nagant Funko Pop
Fatal Accident In Nashville Tn Today
Sara Carter Fox News Photos
Craigslist Sparta Nj
Campaign Blacksmith Bench
Nfl Espn Expert Picks 2023
Renfield Showtimes Near Regal The Loop & Rpx
All Obituaries | Roberts Funeral Home | Logan OH funeral home and cremation
Leslie's Pool Supply Redding California
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.