KEMBAR78
Nodejs | PDF | Computer Engineering | Information Technology
0% found this document useful (0 votes)
8 views8 pages

Nodejs

Uploaded by

gargswyam62
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)
8 views8 pages

Nodejs

Uploaded by

gargswyam62
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
You are on page 1/ 8

Introduction & Setup

i. Node.js is a JavaScript runtime built on Chrome’s V8 engine.


ii. It enables JavaScript to run outside the browser.
iii. Uses a non-blocking, event-driven architecture for handling multiple tasks efficiently.

Practice
1. Install Node.js and check the version:
node -v
npm -v

2. Write a simple script (app.js):


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

3. Run it in the terminal:


node app.js

Core Concepts & Global Objects


i. Global Objects: Available in all Node.js modules.
ii. setTimeout(): Executes a function after a given delay.
iii. setInterval(): Executes a function repeatedly after a fixed interval.
iv. _dirname: Directory of the current module.
v. _filename: Filename of the current module.

Practice
1. Write a script using global objects (global.js):
console.log("Current Directory:", __dirname);
console.log("Current File:", __filename);
setTimeout(() => console.log("Hello after 2 seconds"), 2000);
setInterval(() => console.log("Repeating every 3 seconds"), 3000);
2. Run it in the terminal:
Node global.js

Modules & require()


• Creating and importing modules
• module.exports and require()
Notes
• Built-in Modules: fs, http, os, path, etc.
• Custom Modules: You can create your own modules.
Practice
1. Create a module (math.js):
function add(a, b) {
return a + b;
}
module.exports = add;

2. Use it in another file (app.js):


const add = require('./math');
console.log(add(5, 3)); // Output: 8

3. Run:
node app.js

File System (fs module)


• fs.readFile(): Reads a file asynchronously.
• fs.writeFile(): Writes data to a file.
• fs.appendFile(): Appends data to a file.

Practice
1. Read a file (fileReader.js):

const fs = require('fs');
fs.readFile('data.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});

2. Write to a file (fileWriter.js):

const fs = require('fs');
fs.writeFile('output.txt', 'Hello, Node.js!', (err) => {
if (err) throw err;
console.log("File written successfully");
});
HTTP Module (Creating a Server)
• Creating a basic HTTP server
• Handling requests & responses
Notes
• http.createServer(): Creates an HTTP server.
• res.writeHead(): Sets response headers.
• res.end(): Ends the response.

Practice
1. Create a server (server.js):

const http = require('http');


const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, Node.js!');
});
server.listen(3000, () => console.log('Server running on port 3000'));

2. Run the server:

node server.js

3. Open http://localhost:3000 in your browser.

Express.js (Web Framework)


• Installing & setting up Express
• Creating routes
Notes
• Express simplifies building web servers in Node.js.
• app.get(): Defines GET routes.
• app.listen(): Starts the server.

Install npm
npm init -y
Practice
1. Install Express:

npm install express

2. Create a simple Express server (server.js):


const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Hello Express!'));
app.listen(3000, () => console.log('Server running on port 3000'));

3. Run and test in the browser.


http://localhost:3000/

Working with JSON & APIs


• Handling JSON data in Node.js
• Making HTTP requests using fetch() and axios
• Creating a simple REST API
Notes
• JSON (JavaScript Object Notation) is a lightweight format for data exchange.
• Express.js makes it easy to build REST APIs.
• Use axios for making API requests.
Practice
1. Create a simple REST API (api.js):

const express = require('express');


const app = express();
app.use(express.json());

let users = [{ id: 1, name: "Deepak" }];

app.get('/users', (req, res) => res.json(users));


app.post('/users', (req, res) => {
users.push({ id: users.length + 1, name: req.body.name });
res.send("User added!");
});

app.listen(3000, () => console.log('Server running on port 3000'));


2. Test with Postman or a browser.

Express Router & Middleware


1. Express Router
Express.js provides a built-in router to help you manage routes efficiently, especially in large
applications. The router allows you to group related routes and export them as separate
modules.
2. Middleware in Express
Middleware functions are functions that execute during the request-response cycle. They
have access to the req and res objects and can modify them before sending a response.
Types of Middleware
1. Application-Level Middleware – Applies to all requests.
2. Router-Level Middleware – Specific to an Express Router.
3. Built-in Middleware – Provided by Express (e.g., express.json()).
4. Third-Party Middleware – Installed via npm (e.g., cors).

Notes
• Middleware functions modify requests before they reach route handlers.
• Routers help in structuring large applications.

Practice
1. Create a middleware (middleware.js):

function logger(req, res, next) {


console.log(`${req.method} ${req.url}`);
next(); // Move to the next middleware
}

module.exports = logger;

2. Use it in Express (server.js):

const express = require('express');


const logger = require('./middleware');
const app = express();
app.use(logger);
app.get('/', (req, res) => res.send('Middleware in action!'));
app.listen(3000, () => console.log('Server running on port 3000'));

Create CRUD API (GET / PUT/ UPDATE/ DELETE)


1. Install Node.js and Express

mkdir my-api // Create a folder


cd my-api // Change directory
npm init -y // initial packages.json file

Install Express
npm install express
2. Create a Basic API
Create an index.js file and add the following code:
const express = require('express');
const app = express();
const PORT = 5000;

// Middleware to parse JSON


app.use(express.json());

// Sample data
let users = [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Doe' }
];

// Routes
app.get('/', (req, res) => {
res.send('Welcome to My API');
});

// Get all users


app.get('/users', (req, res) => {
res.json(users);
});

// Get a single user by ID


app.get('/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
user ? res.json(user) : res.status(404).send('User not found');
});

// Create a new user


app.post('/users', (req, res) => {
const newUser = { id: users.length + 1, name: req.body.name };
users.push(newUser);
res.status(201).json(newUser);
});

// Update a user
app.put('/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).send('User not found');
user.name = req.body.name;
res.json(user);
});

// Delete a user
app.delete('/users/:id', (req, res) => {
users = users.filter(u => u.id !== parseInt(req.params.id));
res.send('User deleted');
});

// Start the server


app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});

3. Run the API


Nodemon index.js
Your API will be available at http://localhost:5000
4. Test with Postman or Curl
• Get all users → GET http://localhost:5000/users
• Get user by ID → GET http://localhost:5000/users/1
• Create user → POST http://localhost:5000/users with JSON { "name": "New User" }
• Update user → PUT http://localhost:5000/users/1 with JSON { "name": "Updated User" }
• Delete user → DELETE http://localhost:5000/users/1

You might also like