0% found this document useful (0 votes)
1 views5 pages

Node Js Tutorial

Uploaded by

tricka325
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views5 pages

Node Js Tutorial

Uploaded by

tricka325
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Node.

js Tutorial for Beginners

1 What is Node.js?

Node.js is a runtime environment that allows you to run JavaScript outside the browser, on
the server side. It is built on Chrome’s V8 JavaScript engine, making it fast and efficient for
building scalable, non-blocking applications like web servers, APIs, or real-time apps.

2 Setup and Installation

2.1 Prerequisites
• Basic knowledge of JavaScript (variables, functions, async/await, etc.).
• A computer with an internet connection.

2.2 Steps to Install Node.js


1. Download Node.js: Visit https://nodejs.org and download the LTS (Long-Term
Support) version for stability. Install it by following the installer prompts (available for
Windows, macOS, Linux).
2. Verify Installation: Open a terminal and run:
1 node -- version
2 npm -- version

3. Create a Project Folder:


1 mkdir my - node - app
2 cd my - node - app
3 npm init -y

3 Your First Node.js Program

1. Create a file named app.js:


1 console . log (" Hello , Node . js !") ;

2. Run the file:


1 node app . js

Output: Hello, Node.js!

1
4 Core Concepts

4.1 Modules
Node.js uses a modular system to organize code. You can use built-in modules or create your
own.

4.1.1 Using a Built-in Module (e.g., fs for File System)


1 const fs = require (" fs ") ;
2
3 // Write to a file
4 fs . writeFileSync (" example . txt " , " Hello , Node . js !") ;
5
6 // Read from a file
7 const data = fs . readFileSync (" example . txt " , " utf -8") ;
8 console . log ( data ) ; // Output : Hello , Node . js !

4.1.2 Creating a Custom Module


Create math.js:
1 const add = (a , b ) = > a + b ;
2 module . exports = { add };

Use it in app.js:
1 const math = require ("./ math ") ;
2 console . log ( math . add (2 , 3) ) ; // Output : 5

4.2 NPM (Node Package Manager)


NPM lets you install and manage third-party packages.
• Install a package (e.g., lodash):
1 npm install lodash

• Use it in app.js:
1 const _ = require (" lodash ") ;
2 console . log ( _ . chunk ([1 , 2 , 3 , 4] , 2) ) ; // Output : [[1 , 2] , [3 , 4]]

4.3 Asynchronous Programming


Node.js is non-blocking, using callbacks, promises, or async/await for async operations.
1 const fs = require (" fs ") . promises ;
2
3 async function readFile () {
4 try {
5 const data = await fs . readFile (" example . txt " , " utf -8") ;
6 console . log ( data ) ;
7 } catch ( err ) {
8 console . error (" Error :" , err ) ;
9 }
10 }

2
11
12 readFile () ; // Output : Hello , Node . js !

4.4 Event-Driven Architecture


Node.js uses an event loop to handle asynchronous events.
1 const EventEmitter = require (" events ") ;
2 const myEmitter = new EventEmitter () ;
3
4 myEmitter . on (" greet " , () = > {
5 console . log (" Hello , Event !") ;
6 }) ;
7
8 myEmitter . emit (" greet ") ; // Output : Hello , Event !

5 Building a Simple Web Server

Node.js is great for creating servers. Here is an example using the built-in http module:
1 const http = require (" http ") ;
2
3 const server = http . createServer (( req , res ) = > {
4 res . statusCode = 200;
5 res . setHeader (" Content - Type " , " text / plain ") ;
6 res . end (" Hello from Node . js server !") ;
7 }) ;
8
9 server . listen (3000 , () = > {
10 console . log (" Server running at http :// localhost :3000") ;
11 }) ;

Run node app.js and open http://localhost:3000 in a browser to see the message.

6 Building a Simple REST API with Express

Express is a popular Node.js framework for building web apps and APIs.
1. Install Express:
1 npm install express

2. Create a basic API in app.js:


1 const express = require (" express ") ;
2 const app = express () ;
3
4 app . use ( express . json () ) ; // Parse JSON bodies
5
6 // Sample data
7 let users = [
8 { id : 1 , name : " Alice " } ,
9 { id : 2 , name : " Bob " } ,
10 ];
11
12 // GET : Fetch all users

3
13 app . get ("/ api / users " , ( req , res ) = > {
14 res . json ( users ) ;
15 }) ;
16

17 // POST : Add a user


18 app . post ("/ api / users " , ( req , res ) = > {
19 const user = { id : users . length + 1 , name : req . body . name };
20 users . push ( user ) ;
21 res . status (201) . json ( user ) ;
22 }) ;
23
24 app . listen (3000 , () = > {
25 console . log (" Server running at http :// localhost :3000") ;
26 }) ;

3. Test the API:


• Run node app.js.
• Use a tool like Postman or curl:
1 curl http :// localhost :3000/ api / users

Output: ["id":1,"name":"Alice","id":2,"name":"Bob"]
1 curl -X POST -H " Content - Type : application / json " -d ’ {" name ":"
Charlie "} ’ http :// localhost :3000/ api / users

Output: "id":3,"name":"Charlie"

7 Next Steps

• Learn More Modules: Explore path, url, os, or third-party packages like axios for
HTTP requests.
• Connect to a Database: Use mongoose for MongoDB or pg for PostgreSQL.
• Deploy Your App: Try platforms like Vercel, Heroku, or AWS.
• Error Handling: Add middleware in Express to handle errors gracefully.
• Explore Async Patterns: Dive deeper into promises, async/await, or streams.

8 Additional Notes

• Debugging: Use console.log or tools like VS Code Debugger for Node.js.


• Environment Variables: Use the dotenv package to manage sensitive data:
1 npm install dotenv

1 require (" dotenv ") . config () ;


2 console . log ( process . env . MY_SECRET ) ; // From . env file

• Resources:
– Official Node.js Docs: https://nodejs.org
– Express Docs: https://expressjs.com

4
– Free Tutorials: MDN, freeCodeCamp, or YouTube channels like Traversy Media.

You might also like