Introduction to Node.js
Node.js allows us to run JavaScript outside the web browser. It is commonly used to build web servers, APIs, and backend applications.
In this tutorial, we will learn what Node.js is, how it works, and how to write our first Node.js program using simple examples.
What is Node.js?
Node.js is a JavaScript runtime environment. It allows us to execute JavaScript code outside a web browser.
For example, Samadhan can write JavaScript code to create a server, read files, or connect an application to a database using Node.js.
Before Node.js, JavaScript was mainly used in web browsers. Node.js made it possible to use JavaScript for backend development too.
Why Do We Use Node.js?
- To build backend applications using JavaScript.
- To create web servers and REST APIs.
- To read and write files.
- To connect applications with databases.
- To build real-time applications such as chat applications.
How Does Node.js Work?
Look at the diagram below. It shows how JavaScript code is executed by Node.js outside the browser.
JavaScript Code
Written by Samadhan or Pradnya
Code is executed using
Node.js Runtime
Executes JavaScript outside the browser
Output / Application
Console output, server, API, or file operation
Your First Node.js Program
Let us write a simple program. Pradnya wants to display a welcome message and two student names in the terminal.
Step 1: Create a File
Create a file named app.js. The .js extension represents a JavaScript file.
Step 2: Write the Code
console.log("Welcome to Node.js!");
console.log("Student 1: Samadhan");
console.log("Student 2: Pradnya");
Step 3: Run the Program
Open the terminal in the folder containing app.js and execute:
node app.js
Step 4: Expected Output
Welcome to Node.js!
Student 1: Samadhan
Student 2: Pradnya
console.log()displays a message in the terminal.app.jsis the JavaScript file we created.node app.jstells Node.js to execute that file.
Program Execution Flow
When Pradnya runs the command, Node.js reads the file, executes the statements, and displays the output.
Node.js vs Browser JavaScript
| Browser JavaScript | Node.js |
|---|---|
| Runs inside a web browser. | Runs outside the browser. |
| Can interact with the webpage DOM. | Provides APIs for files and operating-system tasks. |
| Commonly handles webpage interactions. | Commonly handles servers and backend logic. |
| Example: button click handling. | Example: creating an HTTP server. |
Important Points
- Node.js is a JavaScript runtime environment.
- It executes JavaScript outside a web browser.
- Node.js is commonly used for servers and APIs.
console.log()displays output in the terminal.- Use
node app.jsto execute the example file.
Summary
Node.js allows developers to run JavaScript outside the browser.
We can use it to build servers, APIs, and backend applications.
In our first program, we created app.js, executed it using
node app.js, and displayed messages in the terminal.