0% found this document useful (0 votes)
3 views14 pages

Node.js Installation and CRUD Guide

This document provides a comprehensive guide on installing Node.js, creating a basic HTTP server, and performing CRUD operations using both in-memory storage and MongoDB. It includes code examples for handling HTTP requests, utilizing various Node.js modules, and testing the API with Postman. Additionally, it covers asynchronous programming techniques such as callbacks, promises, and async/await.

Uploaded by

alapatipranavi
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)
3 views14 pages

Node.js Installation and CRUD Guide

This document provides a comprehensive guide on installing Node.js, creating a basic HTTP server, and performing CRUD operations using both in-memory storage and MongoDB. It includes code examples for handling HTTP requests, utilizing various Node.js modules, and testing the API with Postman. Additionally, it covers asynchronous programming techniques such as callbacks, promises, and async/await.

Uploaded by

alapatipranavi
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

how to install node js

Windows
1. Download the installer

○ Go to the official [Link] website: [Link]

○ Choose the LTS (Long Term Support) version for stability.

2. Run the installer

○ Double-click the .msi file you downloaded.

3. Follow the setup wizard

○ Accept the license.

○ Keep default settings, ensure "Add to PATH" is checked.

Verify installation
Open Command Prompt or PowerShell and run:

node -v
npm -v

http module in nodejs

const http = require('http');

// Create a server
const server = [Link]((req, res) => {
[Link](200, { 'Content-Type': 'text/plain' }); // Status and headers
[Link]('Hello, World!'); // Response body
});

// Listen on port 3000


[Link](3000, () => {
[Link]('Server running at [Link]
});

fs Module

const fs = require('fs');

// Asynchronous file read


[Link]('[Link]', 'utf8', (err, data) => {
if (err) {
[Link]('Error reading the file:', err);
return;
}
[Link]('File content:');
[Link](data);
});

Output:

File content:
Hello, this is a file read example.
[Link] is awesome!

Path Module

// Import the built-in 'path' module


const path = require('path');

// Example file path


const filePath = '/Users/john/Documents/project/[Link]';

// Get the base name (i.e., the file name)


const baseName = [Link](filePath);
[Link]('Base Name:', baseName); // Output: [Link]

// Get the directory name


const dirName = [Link](filePath);
[Link]('Directory Name:', dirName); // Output:
/Users/john/Documents/project

// Get the file extension


const extName = [Link](filePath);
[Link]('Extension Name:', extName); // Output: .js

// Join paths
const newPath = [Link]('/Users/john', 'Documents', 'project',
'[Link]');
[Link]('Joined Path:', newPath); // Output:
/Users/john/Documents/project/[Link]

// Resolve absolute path


const absolutePath = [Link]('[Link]');
[Link]('Absolute Path:', absolutePath); // Output: Full absolute
path to [Link]

// Normalize a messy path


const messyPath = '/Users/john/../john/Documents//project///[Link]';
const normalized = [Link](messyPath);
[Link]('Normalized Path:', normalized); // Output:
/Users/john/Documents/project/[Link]

Url Module

const url = require('url');


const parsed = [Link]('/products?id=10&name=pen', true);
[Link]([Link]); // /products
[Link]([Link]); // pen

Callback

// Step 1 function
function step1(value, callback) {
callback(value + 10, false); // false means no error
}

// Step 2 function
function step2(value, callback) {
callback(value * 2, false);
}

// Step 3 function
function step3(value, callback) {
callback(value - 5, false);
}

// Starting the chain


step1(10, function(result1, error) {
if (!error) {
step2(result1, function(result2, error) {
if (!error) {
step3(result2, function(result3, error) {
if (!error) {
[Link]("Final Result:", result3);
}
});
}
});
}
});

Promises

// Step 1 function returning a Promise


function step1(value) {
return [Link](value + 10);
}

// Step 2 function returning a Promise


function step2(value) {
return [Link](value * 2);
}

// Step 3 function returning a Promise


function step3(value) {
return [Link](value - 5);
}

// Chaining Promises
step1(10)
.then(result1 => step2(result1))
.then(result2 => step3(result2))
.then(result3 => [Link]("Final Result:", result3))
.catch(error => [Link]("Error:", error));

// Example Promises
const p1 = [Link]('Like if you understood callbacks');
// const p2 = [Link]('Rejected'); // Uncomment to test
rejection
const p3 = 100; // This will be treated as an already resolved value
const p4 = new Promise((resolve) => {
setTimeout(resolve, 1000, 'Subscribe for more updates');
});

// [Link]: waits for all Promises to resolve


[Link]([p1, p3, p4])
.then(values => [Link]("[Link] results:", values));

// [Link]: gets results of all Promises, whether fulfilled


or rejected
[Link]([p1, /*p2*/ p3, p4])
.then(results => [Link]("[Link] results:",
results));

Async/Await
// Step 1: A function that returns a Promise
function step1(value, error) {
return new Promise((resolve, reject) => {
if (!error) {
resolve(value + 10); // If no error → resolve with value +
10
} else {
reject('Something went wrong'); // If error → reject
}
});
}

// Step 2: Async function using await


async function result() {
let result1 = await step1(10, false); // Wait for step1 to
complete
[Link](result1); // Log the resolved value
return result1; // Return it
}

// Step 3: Another async function returning a resolved Promise


async function result2() {
let result = await [Link](5); // Wait for a promise that
resolves to 5
return result;
}

// Step 4: Calling result() and handling with .then()


result().then((finalValue) => {
[Link](finalValue); // Prints the returned value from
result()
});

CRUD OPERATIONS IN Nodejs


const http = require('http');
const url = require('url');

let products = [
{ id: 1, name: 'Pen', price: 10 },
{ id: 2, name: 'Book', price: 50 }
];

const server = [Link]((req, res) => {


const parsedUrl = [Link]([Link], true);
const path = [Link];
const method = [Link];

// Set JSON response header


[Link]('Content-Type', 'application/json');

// CREATE (POST /products)


if (path === '/products' && method === 'POST') {
let body = '';
[Link]('data', chunk => { body += chunk; });
[Link]('end', () => {
const newProduct = [Link](body);
[Link] = [Link] ? products[[Link] -
1].id + 1 : 1;
[Link](newProduct);
[Link](201);
[Link]([Link]({ message: 'Product added', product:
newProduct }));
});
}

// READ (GET /products)


else if (path === '/products' && method === 'GET') {
[Link](200);
[Link]([Link](products));
}
// UPDATE (PATCH /products?id=1)
else if (path === '/products' && method === 'PATCH') {
const id = parseInt([Link]);
let body = '';
[Link]('data', chunk => { body += chunk; });
[Link]('end', () => {
const updates = [Link](body);
const product = [Link](p => [Link] === id);
if (product) {
[Link](product, updates);
[Link](200);
[Link]([Link]({ message: 'Product updated', product
}));
} else {
[Link](404);
[Link]([Link]({ message: 'Product not found' }));
}
});
}

// DELETE (DELETE /products?id=1)


else if (path === '/products' && method === 'DELETE') {
const id = parseInt([Link]);
const index = [Link](p => [Link] === id);
if (index !== -1) {
const deleted = [Link](index, 1);
[Link](200);
[Link]([Link]({ message: 'Product deleted', product:
deleted[0] }));
} else {
[Link](404);
[Link]([Link]({ message: 'Product not found' }));
}
}

// 404 Not Found


else {
[Link](404);
[Link]([Link]({ message: 'Not Found' }));
}
});

[Link](3000, () => {
[Link]('Server running at [Link]
});

Save and run the server

1. Save your code as [Link] (or any name you want).


2. In your terminal, navigate to the folder where [Link] is saved.
3. Run:

node [Link]

4. You should see:

Server running at [Link]

2. Open Postman

You’ll test each HTTP method (GET, POST, PATCH, DELETE) using Postman.

3. Testing the API

A) GET — Read products

 Method: GET
 URL: [Link]
 Body: (none)
 Click Send → You should get:

[
{ "id": 1, "name": "Pen", "price": 10 },
{ "id": 2, "name": "Book", "price": 50 }
]
B) POST — Add a new product

 Method: POST
 URL: [Link]
 Go to Body → raw → JSON and enter:

{ "name": "Pencil", "price": 5 }

 Click Send → Response:

{ "message": "Product added", "product": { "id": 3, "name": "Pencil",


"price": 5 } }

C) PATCH — Update a product

 Method: PATCH
 URL: [Link]
 Body → raw → JSON:

{ "price": 15 }

 Click Send → Response:

{ "message": "Product updated", "product": { "id": 1, "name": "Pen",


"price": 15 } }

D) DELETE — Remove a product

 Method: DELETE
 URL: [Link]
 Click Send → Response:

{ "message": "Product deleted", "product": { "id": 2, "name": "Book",


"price": 50 } }

CONNECTING TO MONGODB

// [Link]
const http = require('http');
const { MongoClient, ObjectId } = require('mongodb');
const url = 'mongodb://[Link]:27017';
const dbName = 'testdb';
let productsCollection;

// Connect to MongoDB first


async function connectDB() {
const client = new MongoClient(url);
await [Link]();
[Link]('Connected to MongoDB');
const db = [Link](dbName);
productsCollection = [Link]('products');
}
connectDB();

const server = [Link](async (req, res) => {


const { method, url: reqUrl } = req;

// GET all products


if (reqUrl === '/products' && method === 'GET') {
try {
const products = await
[Link]().toArray();
[Link](200, { 'Content-Type': 'application/json'
});
[Link]([Link](products));
} catch (err) {
[Link](500);
[Link]([Link]({ error: [Link] }));
}
}

// POST add a product


else if (reqUrl === '/products' && method === 'POST') {
let body = '';
[Link]('data', chunk => { body += chunk; });
[Link]('end', async () => {
try {
const newProduct = [Link](body);
const result = await
[Link](newProduct);
[Link](201, { 'Content-Type':
'application/json' });
[Link]([Link]({
message: 'Product added',
product: { _id: [Link], ...newProduct }
}));
} catch (err) {
[Link](500);
[Link]([Link]({ error: [Link] }));
}
});
}

// PATCH update product by ID


else if ([Link]('/products/') && method === 'PATCH') {
const id = [Link]('/')[2];
let body = '';
[Link]('data', chunk => { body += chunk; });
[Link]('end', async () => {
try {
const updates = [Link](body);
const result = await [Link](
{ _id: new ObjectId(id) },
{ $set: updates }
);
[Link](200, { 'Content-Type':
'application/json' });
[Link]([Link]({ message: 'Product updated',
modifiedCount: [Link] }));
} catch (err) {
[Link](500);
[Link]([Link]({ error: [Link] }));
}
});
}
// DELETE product by ID
else if ([Link]('/products/') && method === 'DELETE') {
const id = [Link]('/')[2];
try {
const result = await [Link]({ _id:
new ObjectId(id) });
[Link](200, { 'Content-Type': 'application/json'
});
[Link]([Link]({ message: 'Product deleted',
deletedCount: [Link] }));
} catch (err) {
[Link](500);
[Link]([Link]({ error: [Link] }));
}
}

// 404 for unknown routes


else {
[Link](404, { 'Content-Type': 'application/json' });
[Link]([Link]({ error: 'Route not found' }));
}
});

[Link](7000, () => {
[Link](' Server running on [Link]
}); [Link]([Link]({ message: 'Not Found' }));
}
});

[Link](7000, () => {
[Link]('Server running at [Link]
});

 Install [Link] (already done if you’re running Node programs)


 Install MongoDB locally and make sure it’s running (mongod service started)
 Install MongoDB driver in your project:
npm install mongodb

How to Test in Postman

1. Start server

node [Link]

2. GET all products


o Method: GET
o URL: [Link]
3. POST a new product
o Method: POST
o URL: [Link]
o Headers:

Content-Type: application/json

o Body (raw JSON):

{ "name": "Pen", "price": 20, "brand": "Cello" }

4. PATCH update a product


o Method: PATCH
o URL: [Link]
o Headers:

Content-Type: application/json

o Body:

{ "price": 25 }

5. DELETE a product
o Method: DELETE
o URL: [Link]

You might also like