Installing VS Code and Node.js on Windows
Installing VS Code and Node.js on Windows
LAB-2
HOW TO INSTALL VISUAL STUDIO CODE ON
WINDOWS?
→ Steps to install visual studio code on windows :
STEP: 1 Visit the official website VISUAL STUDIO CODE and using any web
browser like GOOGLE CHROME and MICROSOFT EDGE, etc..,
STEP:2 Press the “DOWNLOAD FOR WINDOWS” button on the website to start
the download of the visual studio code application.
STEP: 3 when the download finishes, then the VISUAL STUDIO CODE ICON
appears in the downloads folder.
STEP: 4 Click on the installer icon to start the installation process of the visual
studio code.
STEP: 5 After the installer opens, it will ask you to accept the terms and conditions
of the visual studio code. Click on I accept the agreement and then click the next
button.
STEP:6
Choose the location data for running the visual studio code. It will then ask you to
browse the location. Then click the next button.
STEP:7
Then it will ask to begin the installation setup. Click on the install button.
STEP:8
After clicking on Install, it will take about 1 minute to install the Visual Studio Code
on your device.
STEP:9
After the Installation setup for Visual Studio Code is finished, it will show a
window like this below. Tick the "Launch Visual Studio Code" checkbox and then
click Next.
STEP: 10 After the previous step, the Visual Studio Code window opens
successfully. Now you can create a new file in the Visual Studio Code window and
choose a language of yours to begin your programming journey
INSTALLATION PROCESS ON [Link] :
How to Install [Link] on Windows
Installing [Link] on Windows is a straightforward process, but it's essential to follow
the right steps to ensure smooth setup and proper functioning of Node Package
Manager (NPM), which is crucial for managing dependencies and packages. This
guide will walk you through the official site, NVM, Windows Subsystem, and
Package Manager for Windows 7, 8, 10, and 11.
Method 1: Use the Official Website
Follow these steps to install the [Link] on your Windows:
C:\Users\Admin> node -v
Windows Subsystem for Linux (WSL) is a great option for those who prefer
a Linux environment. You can run a Linux distribution on your Windows machine
and use Linux tools like apt-get for installation.
This will install the WSL feature and the default Ubuntu distribution.
Step 2: Set up a Linux Distribution
Once WSL is installed, launch the Ubuntu (or another Linux distro) app from
the Start Menu and set up your Linux distribution by creating a user and password.
Open the WSL terminal (Ubuntu or your chosen distribution) and update your
package list:
sudo apt update
Once the update is done, Install [Link] using the following command:
sudo apt install nodejs
sudo apt install npm
Once the installation is complete, verify the installation by entering the following
command:
node -v
npm -v
Method 4: Install [Link] & NPM using WPM
Windows 10 and 11 users can use winget, the Windows Package Manager, to easily
install [Link].
→ Verify Installation for [Link] and NPM
After installation, check if [Link] is installed correctly:
node -v
npm -v
[Link](3000, () => {
[Link]("Server running at [Link]
});
// [Link]
const http = require("http");
How to run:
1. Save as [Link].
2. Run: node [Link]
3. Then open a browser at [Link] and you see "Hello, World!".
// [Link]
[Link]("Hello, World!");
});
[Link](port, () => {
});
npm init -y
npm install express
[Link] run: node [Link]
1. Routing in [Link]
Routing defines how your Express app responds to client requests for specific
endpoints (paths and methods).
[Link]("Home Page");
});
[Link]("About Page");
});
2. HTTP Methods in [Link]
[Link]("Form submitted");
});
});
});
3. Middleware in [Link]
Middleware are functions that run during the lifecycle of a request to the server.
They can: 1. Modify request/response objects
// Global middleware
[Link](`${[Link]} ${[Link]}`);
});
// 2. Route Parameters
[Link]('/users/:id', (req, res) => {
const userId = [Link];
[Link](`User ID: ${userId}`);
});
// 3. Query Parameters
[Link]('/search', (req, res) => {
const searchTerm = [Link].q;
[Link](`Search term: ${searchTerm}`);
});
[Link](port, () => {
[Link](`Server listening at [Link]
});
OUTPUTS:
// [Link]
const express = require('express');
const app = express();
[Link]([Link]()); // parse JSON bodies
Output:
1. POST /items — Add data
Request:
http
CopyEdit
POST /items HTTP/1.1
Content-Type: application/json
{
"name": "Laptop"
}
Response:
json
CopyEdit
{
"id": 1,
"name": "Laptop"}
json
CopyEdit
{
"name": "Phone"}
Response:
json
CopyEdit
{
"id": 2,
"name": "Phone"}
OUTPUT :
Visit the home page: Hello, this is the main route!
2. Express JS – Templating, Form Data
[Link] facilitates both templating for dynamic HTML generation and handling
form data submitted from clients.
1. Templating in [Link]:
Purpose : Templating engines allow embedding dynamic data and logic within static
HTML structures, generating personalized content for users.
Common engines: Popular choices include Ejs (Embedded JavaScript), Pug (formely
jade), and Handlebars.
Setup:
1. Install the desired templating engine (e.g., npm install ejs).
2. Configure Express to use the engine: [Link]('view engine', 'ejs');
3. Specify the directory where your template files are located: [Link]('views',
[Link](__dirname, 'views'));
// Specify the directory where your EJS templates (views) are located
[Link](‘views’, [Link](__dirname, ‘views’));
Output:
User Information
coding
reading
hiking
// Start server
[Link](3000, () => {
[Link](“Server is running on [Link]
});
OUTPUT:
Form Example
Name: [__________]
Email: [_________]
[Submit]
After filling and submitting:
Received data:
Name: Disney
Email: disney@[Link]
Explanation:
express-session:
This middleware creates and manages sessions. It assigns a unique session ID to each
user and stores session data on the server (or a chosen session store).
cookie-parser:
This middleware parses incoming request cookies, making them accessible via
[Link].
Session ID Cookie:
express-session automatically sets a session ID cookie (typically named [Link])
in the user's browser, which is used to identify the session on subsequent requests.
secret:
A crucial security measure, used to sign the session ID cookie, preventing tampering.
secure and httpOnly cookie options:
Enhance security by ensuring the cookie is only sent over HTTPS and cannot be
accessed by client-side JavaScript, respectively.
[Link]:
This object is provided by express-session and allows you to store and retrieve
session-specific data.
isAuthenticated middleware:
A common pattern to protect routes, ensuring only authenticated users can access
them.
[Link]():
Used to end a session and remove its data from the session store.
[Link]():
Removes the session ID cookie from the client's browser.
// Middleware
[Link](cookieParser());
[Link]([Link]({ extended: true }));
// Configure session
[Link](session({
secret: 'mysecretkey123', // Secret for signing the session ID cookie
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 } // Session expires after 1 minute
}));
// Homepage
[Link]('/', (req, res) => {
if ([Link]) {
[Link](`<h2>Welcome back, ${[Link]}!</h2>
<a href="/logout">Logout</a>`);
} else {
[Link](`<form method="POST" action="/login">
<input type="text" name="username" placeholder="Enter username"
required />
<button type="submit">Login</button>
</form>`);
}
});
// Login handler
[Link]('/login', (req, res) => {
const username = [Link];
[Link] = username;
[Link]('user', username); // Set a cookie
[Link]('/');
});
// Logout handler
[Link]('/logout', (req, res) => {
[Link]('user'); // Clear cookie
[Link](); // Destroy session
[Link]('/');
});
// Start server
[Link](3000, () => {
[Link](“Server is running on [Link]
});
OUTPUT:
Enter username: cartoon
login
Welcome back, cartoon
Logout
// Hash the user’s password once (in real apps, this would be stored already)
[Link](‘1234’, 10, (err, hash) => {
users[0].passwordhash = hash;
});
// Middleware
[Link]([Link]({ extended: true }));
[Link](session({
secret: ‘secretkey123’,
resave: false,
saveunitialized: false
}));
/ Routes
[Link]('/', (req, res) => {
if ([Link]) {
[Link](<h2>Welcome, ${[Link]}!</h2><a
href="/logout">Logout</a>);
} else {
[Link](`<form method="POST" action="/login">
<input name="username" placeholder="Username" required />
<input name="password" type="password" placeholder="Password"
required />
<button type="submit">Login</button>
</form>`);
}
});
[Link](3000, () => {
[Link](Server running on [Link]
});
OUTPUT:
Username:
Password:
Login
// MongoDB connection
[Link](‘mongodb://localhost:27017/mydb’, {
useNewUrlparser: true,
useUnifiedTopology: true
})
.then(() => [Link](‘ MongoDB connected’))
.catch(err => [Link](‘ MongoDB connection error:’, err));
// CREATE
[Link](‘/users’, async (req, res) => {
try {
const user = new User([Link]);
await [Link]();
[Link](user);
} catch (err) {
[Link](400).send(err);
}
});
// READ ONE
[Link](‘/users/:id’, async (req, res) => {
try {
const user = await [Link]([Link]);
if (!user) return [Link](404).send(‘User not found’);
[Link](user);
} catch (err) {
[Link](400).send(err);
}
});
// UPDATE
[Link](‘/users/:id’, async (req, res) => {
try {
const user = await [Link](
[Link],
[Link],
{ new: true }
);
if (!user) return [Link](404).send(‘User not found’);
[Link](user);
} catch (err) {
[Link](400).send(err);
}
});
// DELETE
[Link](‘/users/:id’, async (req, res) => {
try {
const user = await [Link]([Link]);
if (!user) return [Link](404).send(‘User not found’);
[Link](‘User deleted’);
} catch (err) {
[Link](400).send(err);
}
});
// Start Server
[Link](3000, () => {
[Link](‘Server is running on [Link]
});
[Link]:
<!DOCTYPE html>
<html>
<title>Test SPA</title>
</head>
<body>
<h1>Hello from [Link]!</h1>
</body>
</html>
[Link]:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser')
const app = express();
const PORT = 3000;
[Link]([Link]());
[Link]([Link]('public'));
// Create
[Link]('/api/users', (req, res) => {
const user = [Link];
[Link](user);
[Link](201).json({ message: 'User added', user });
});
// Start server
[Link](3000, () =>
[Link]('Server is running on [Link]
);
OUTPUT:
Hello from [Link]
npm start
Folder structure:
my-html-app
|-----[Link]
|-----public/
| |-----[Link]
[Link]:
<!DOCTYPE html>
<html>
<head>
<title>My HTML Page</title>
</head>
<body>
<h1>Hello from [Link]!</h1>
<p>This HTML page is rendered using Express server.</p>
</body>
</html>
[Link]:
Folder Structure:
Waiting-markup-app/
|------public/
| |------[Link]
| |------[Link]
|---------src/
| |-----[Link]
|--------[Link]
|--------[Link]
|-------- .babelrc
[Link]:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Waiting Markup</title>
</head>
<body>
<div id="root"></div>
<script src="/[Link]"></script>
</body>
</html>
[Link]:
[Link]("root").innerHTML = "<h1>Hello, this is my
output!</h1>";
[Link]:
// src/[Link]
import React from 'react';
import ReactDOM from 'react-dom/client';
const root =
[Link]([Link]('root'));
[Link](<App />);
.babelrc:
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
[Link]:
[Link] = {
entry: './src/[Link]',
output: {
path: [Link](__dirname, 'public/'),
filename: '[Link]',
publicPath: '/'
},
module: {
rules: [
{
test: /\.jsx?$/,
use: 'babel-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.js', '.jsx']
},
mode: 'development'
};
[Link]:
[Link](webpackMiddleware(compiler));
[Link]([Link]('public'));
[Link](3000, () => {
[Link]('Server is running on [Link]
});
Folder structure:
My-node-app/
│
├── [Link]
└── components/
├── [Link]
└── [Link]
My-node-app/ [Link]:
[Link] = {
Header,
Footer
};
My-node-app/components/[Link]:
render() {
[Link]("Rendering Content...");
[Link]([Link]);
[Link]();
}
render() {
[Link]("Rendering Sidebar...");
[Link]([Link]);
}
}
Output:
Rendering App...
Rendering Header...
Rendering Content...
This is the main content area.
Rendering Sidebar...
Sidebar info here.
Rendering Footer...
for frontend:
Folder structure:
my-app/
├── backend/
│ └── [Link]
├── frontend/
│ ├── public/
│ │ └── [Link]
│ ├── src/
│ │ ├── [Link]
│ │ └── [Link]
└── [Link]
backend/ [Link]:
const express = require('express');
const cors = require('cors');
[Link](cors());
[Link](5000, () => {
[Link](`Backend running on [Link]
});
frontend/public/[Link]:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>React App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
frontend/src/[Link]:
useEffect(() => {
fetch('[Link]
.then(res => [Link]())
.then(data => setMessage([Link]))
.catch(err => [Link](err));
}, []);
return (
<div>
<h1>React Frontend</h1>
<p>{message ? message : "Loading..."}</p>
</div>
);
};
frontend/src/[Link]:
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
frontend/[Link]:
{
"name": "frontend",
"version": "0.1.0",
"private": "true",
"dependencies": {
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-scripts": "^5.0.1"
},
"scripts": {
"start": "react-scripts start"
},
"proxy": "[Link]
}
Output:
b) Write a program to add styles (CSS & Sass Styling) and display
data.
Folder structure:
node-css-sass-app/
├── public/
│ ├── styles/
│ │ ├── [Link]
├── views/
│ └── [Link]
├── [Link]
Install packages:
npm init -y
npm install express ejs
npm install sass-middleware
node-css-sass-app/public/styles/[Link]:
$primary-color: #3498db;
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 20px;
h1 {
color: $primary-color;
}
ul {
list-style: none;
padding: 0;
li {
background: white;
margin: 10px 0;
padding: 10px;
border-left: 5px solid $primary-color;
}
}
}
node-css-sass-app/views/[Link]:
<!DOCTYPE html>
<html>
<head>
<title>Styled Node App</title>
<link rel="stylesheet" href="/styles/[Link]">
</head>
<body>
<h1>Data List</h1>
<ul>
<% [Link](item => { %>
<li><%= item %></li>
<% }) %>
</ul>
</body>
</html>
node-css-sass-app/[Link]:
// Sass middleware
[Link](
sassMiddleware({
src: [Link](__dirname, 'public', 'styles'),
dest: [Link](__dirname, 'public', 'styles'),
debug: true,
outputStyle: 'compressed',
prefix: '/styles',
})
);
// Static files
[Link]([Link]([Link](__dirname, 'public')));
// Sample data
const data = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];
// Routes
[Link]('/', (req, res) => {
[Link]('index', { data });
});
[Link](port, () => {
[Link](`Server is running on [Link]
});
Output :
+------------------------------+
| Data List | ← blue heading
| |
| ┌────────────────────────┐ |
| | Apple | | ← white box with blue border
| └────────────────────────┘ |
| ┌────────────────────────┐ |
| | Banana | |
| └────────────────────────┘ |
| ... |
+------------------------------+
Output:
Folder structure:
project/
├── views/
│ └── [Link]
├── [Link]
└── [Link]
[Link]:
[Link]('index', {
user: {
name: 'John Doe',
role: 'admin',
},
isLoggedIn: isLoggedIn
});
});
[Link](port, () => {
[Link](`Server is running on [Link]
});
[Link]:
<!DOCTYPE html>
<html>
<head>
<title>Conditional Rendering</title>
</head>
<body>
<% if (isLoggedIn) { %>
<h1>Welcome, <%= [Link] %>!</h1>
<% if ([Link] === 'admin') { %>
<p>You have admin privileges.</p>
<% } else { %>
<p>You are a regular user.</p>
<% } %>
<% } else { %>
<h1>Please log in to continue.</h1>
<% } %>
</body>
</html>
[Link]:
{
"name": "conditional-rendering",
"version": "1.0.0",
"main": "[Link]",
"scripts": {
"start": "node [Link]"
},
"dependencies": {
"ejs": "^3.1.10",
"express": "^4.21.2"
},
"description": "",
"keywords": [],
"author": "",
"license": "ISC",
"type": "commonjs"
}
Outputs:
Output 1:
isLoggedIn is true:
isLoggedIn = true
[Link] = 'admin'
Output 2:
isLoggedIn = false:
Please log in to continue.
/node-list-rendering
├── views
│ └── [Link]
└── [Link]
node-list-rendering/views/[Link]:
[Link](port, () => {
[Link](`Server running at [Link]
});
node-list-rendering/[Link]:
<!DOCTYPE html>
<html>
<head>
<title>User List</title>
</head>
<body>
<h1>List of Users</h1>
<ul>
<% [Link](function(user) { %>
<li><strong><%= [Link] %></strong> - Age: <%= [Link] %></li>
<% }); %>
</ul>
</body>
</html>
List of Users
- Alice - Age: 25
- Bob - Age: 30
- Charlie - Age: 28
c) Write a program for working with different form fields using react
forms.
Folder Structure:
form-app/
├── server/ <-- [Link] + Express backend
│ └── [Link]
├── client/ <-- React frontend
│ ├── src/
│ │ └── [Link]
│ └── [Link]
form-app/server/[Link]:
[Link](cors());
[Link]([Link]());
// GET route
[Link]('/', (req, res) => {
[Link]('Server is up and running!');
});
[Link](PORT, () => {
[Link](`Server is running at [Link]
});
Install packages:
npm init -y
npm install express cors body-parser
node [Link]
form-app/client/src/[Link]:
function App() {
return (
<div className="container">
{/* App Logo */}
<div className="logo-container">
<img src="/[Link]" alt="App Logo" className="logo" />
</div>
form-app/client/[Link]:
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/dom": "^10.4.1",
"@testing-library/jest-dom": "^6.6.4",
"@testing-library/react": "^16.3.0",
"@testing-library/user-event": "^13.5.0",
"react": "^19.1.1",
"react-dom": "^19.1.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Output:
Name:
Email:
Passwor
d:
Submit
my-react-router-app/
│
├── public/
│ └── [Link]
├── src/
│ ├── [Link]
│ ├── [Link]
│ ├── [Link]
│ ├── [Link]
│ └── [Link]
├── [Link]
my-react-router-app/public/[Link]:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/[Link]" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<title>React Router App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
my-react-router-app/src/[Link]:
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</div>
);
}
my-react-router-app/src/[Link]:
import React from 'react';
function Home() {
return (
<div>
<h1>Welcome to My Website</h1>
<p>This is a simple React Router demo app.</p>
</div>
);
}
my-react-router-app/src/[Link]:
function About() {
return (
<div>
<h1>About This App</h1>
<p>This app demonstrates routing in React using React Router.</p>
<p>Built with 😆 by OpenAI and you!</p>
</div>
);
}
my-react-router-app/src/[Link]:
function Contact() {
const [formData, setFormData] = useState({
name: '',
email: '',
message: ''
});
return (
<div>
<h1>Contact Us</h1>
{submitted ? (
<p style={{ color: 'green' }}>
✅ Thank you, <strong>{[Link]}</strong>! Your message has been
sent.
</p>
):(
<form onSubmit={handleSubmit}>
<label>Name:</label><br />
<input
type="text"
name="name"
value={[Link]}
onChange={handleChange}
required
/><br /><br />
<label>Email:</label><br />
<input
type="email"
name="email"
value={[Link]}
onChange={handleChange}
required
/><br /><br />
<label>Message:</label><br />
<textarea
name="message"
value={[Link]}
onChange={handleChange}
required
rows="4"
></textarea><br /><br />
<button type="submit">Send</button>
</form>
)}
</div>
);
}
my-react-router-app/src/[Link]:
my-react-router-app/[Link]:
{
"name": "my-react-router-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.30.1",
"react-scripts": "^0.0.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Output:
Contact: Contact Us
Name:
Email:
Message:
Send
function updateScreen() {
[Link]([Link], 0, 0); // Move cursor to top-left
[Link]([Link]); // Clear screen
// Initial update
updateScreen();
Output:
📅 Current Time:
4:51:38 pm
Install package:
//file: [Link]
const mongoose = require('mongoose');
[Link]('mongodb://localhost:27017/hookDemo', {
useNewUrlParser: true,
useUnifiedTopology: true
});
Folder structure:
node-shared-data-example
├── [Link]
├── [Link]
├── [Link]
└── [Link]
node-shared-data-example/[Link]:
// [Link]
const data = {
message: "Initial message"
};
[Link] = {
getMessage: () => [Link],
setMessage: (newMessage) => {
[Link] = newMessage;
}
};
node-shared-data-example/[Link]:
// [Link]
const sharedData = require('./sharedData');
function updateMessage() {
[Link]("Updated by writer module");
[Link]("✅ Message updated in writer");
}
[Link] = updateMessage;
node-shared-data-example/[Link]:
// [Link]
const sharedData = require('./sharedData');
function readMessage() {
[Link]("📩 Reader got message:", [Link]());
}
[Link] = readMessage;
node-shared-data-example/[Link]:
// [Link]
const updateMessage = require('./writer');
const readMessage = require('./reader');
Output:
Before update:
📩 Reader got message: Initial message
🔹 Updating message...
✅ Message updated in writer
🔹 After update:
📩 Reader got message: Updated by writer module
Go to Network Access
Click Add IP Address
Choose [Link] (allow from anywhere — for dev only!)
Or your IP for security
mongodb+srv://username:<password>@[Link]/database_name?
retryWrites=true&w=majority
Folder structure:
mongo-node-crud
|-------- .env
|-------- [Link]
mongo-node-crud/[Link]:
[Link]([Link]());
mongo-node-crud/ .env :
MONGO_URI=mongodb+srv://admin:admin123@[Link]/
testdb?retryWrites=true&w=majority
PORT=5000
mongo-native-crud
|----- .env
|----- [Link]
mongo-native-crud/[Link]:
require('dotenv').config();
const { MongoClient, ObjectId } = require('mongodb');
try {
await [Link]();
[Link]('✅ Connected to MongoDB');
const db = [Link](dbName);
const users = [Link]('users');
// ----------------------------
// 🔽 INSERT - insertOne()
// ----------------------------
const newUser = { name: 'Alice', email: 'alice@[Link]', age: 25 };
const insertResult = await [Link](newUser);
[Link]('✅ Inserted:', [Link]);
// ----------------------------
// 🔍 READ - find()
// ----------------------------
const allUsers = await [Link]().toArray();
[Link]('📄 All Users:', allUsers);
// ----------------------------
// ✏️UPDATE - updateOne()
// ----------------------------
const updateResult = await [Link](
{ _id: [Link] },
{ $set: { age: 30 } }
);
[Link]('✏️Updated:', [Link], 'document(s)');
// ----------------------------
// ❌ DELETE - remove() is deprecated, use deleteOne()
// ----------------------------
const deleteResult = await [Link]({ _id: [Link] });
[Link](' Deleted:', [Link], 'document(s)');
} catch (err) {
[Link]('❌ Error:', err);
} finally {
await [Link]();
[Link]('🔌 Disconnected');
}
}
main();
mongo-native-crud/ .env:
MONGO_URI=mongodb://localhost:27017
DB_NAME=testdb
Output:
📄 All Users: [
name: 'Alice',
email: 'alice@[Link]',
age: 25
✏️Updated: 1 document(s)
Deleted: 1 document(s)
🔌 Disconnected
Folder structure:
program11a
|------ .env
|------ [Link]
program11a/ .env:
MONGO_URI=mongodb://localhost:27017
program11a/[Link]:
require('dotenv').config();
const { MongoClient } = require('mongodb');
try {
await [Link]();
[Link]('✅ Connected to MongoDB');
// 🔥 Drop Collection
const dropCollectionResult = await [Link]('students').drop();
[Link](' Collection dropped:', dropCollectionResult); // true
// 🔥 Drop Database
const dropDbResult = await [Link]();
[Link](' Database dropped:', dropDbResult); // true
} catch (err) {
[Link]('❌ Error:', err);
} finally {
await [Link]();
[Link]('🔌 Disconnected from MongoDB');
}
}
main();
Output:
Folder structure:
mongo-queries
|------ .env
|------ [Link]
mongo-queries/ .env:
MONGO_URI=mongodb://localhost:27017
mongo-queries/ [Link]:
require('dotenv').config();
const { MongoClient } = require('mongodb');
try {
await [Link]();
[Link]('✅ Connected to MongoDB');
const db = [Link]('companyDB');
const employees = [Link]('employees');
// 🔁 Insert sample records
await [Link]([
{ name: 'Alice', age: 25, dept: 'HR', salary: 3000 },
{ name: 'Bob', age: 30, dept: 'IT', salary: 5000 },
{ name: 'Carol', age: 28, dept: 'IT', salary: 4500 },
{ name: 'Dave', age: 35, dept: 'Finance', salary: 6000 },
{ name: 'Eve', age: 22, dept: 'HR', salary: 3200 }
]);
[Link]('📥 Sample data inserted');
} catch (err) {
[Link]('❌ Error:', err);
} finally {
await [Link]();
[Link]('\n🔌 Disconnected');
}
}
main();
Output:
name: 'Alice',
age: 25,
dept: 'HR',
salary: 3000
},
name: 'Bob',
age: 30,
dept: 'IT',
salary: 5000
},
name: 'Carol',
age: 28,
dept: 'IT',
salary: 4500
},
name: 'Dave',
age: 35,
dept: 'Finance',
salary: 6000
},
name: 'Eve',
age: 22,
dept: 'HR',
salary: 3200
},
name: 'Alice',
age: 25,
dept: 'HR',
salary: 3000
},
name: 'Bob',
age: 30,
dept: 'IT',
salary: 5000
},
{
name: 'Carol',
age: 28,
dept: 'IT',
salary: 4500
},
name: 'Dave',
age: 35,
dept: 'Finance',
salary: 6000
},
name: 'Eve',
age: 22,
dept: 'HR',
salary: 3200
},
name: 'Alice',
age: 25,
dept: 'HR',
salary: 3000
},
name: 'Bob',
age: 30,
dept: 'IT',
salary: 5000
},
name: 'Carol',
age: 28,
dept: 'IT',
salary: 4500
},
name: 'Dave',
age: 35,
dept: 'Finance',
salary: 6000
},
{
_id: new ObjectId('6891df5603e52cad326b62ea'),
name: 'Eve',
age: 22,
dept: 'HR',
salary: 3200
name: 'Alice',
age: 25,
dept: 'HR',
salary: 3000
},
name: 'Bob',
age: 30,
dept: 'IT',
salary: 5000
{
_id: new ObjectId('6891ae61c87819a49997af30'),
name: 'Dave',
age: 35,
dept: 'Finance',
salary: 6000
},
name: 'Dave',
age: 35,
dept: 'Finance',
salary: 6000
},
name: 'Dave',
age: 35,
dept: 'Finance',
salary: 6000
},
name: 'Bob',
age: 30,
dept: 'IT',
salary: 5000
},
name: 'Bob',
age: 30,
dept: 'IT',
salary: 5000
},
name: 'Bob',
age: 30,
dept: 'IT',
salary: 5000
},
name: 'Carol',
age: 28,
dept: 'IT',
salary: 4500
},
age: 28,
dept: 'IT',
salary: 4500
},
name: 'Carol',
age: 28,
dept: 'IT',
salary: 4500
},
name: 'Eve',
age: 22,
dept: 'HR',
salary: 3200
},
name: 'Eve',
age: 22,
dept: 'HR',
salary: 3200
},
name: 'Eve',
age: 22,
dept: 'HR',
salary: 3200
},
name: 'Alice',
age: 25,
dept: 'HR',
salary: 3000
},
name: 'Alice',
age: 25,
dept: 'HR',
salary: 3000
},
name: 'Alice',
age: 25,
dept: 'HR',
salary: 3000
🔌 Disconnected
Folder Structure:
todo-app/
├── views/
│ └── [Link]
├── public/
│ └── [Link]
├── [Link]
├── [Link]
Install packages:
npm init -y
npm install express ejs body-parser uuid
todo-app/views/[Link]:
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
<link rel="stylesheet" href="/[Link]">
</head>
<body>
<h1>To-Do List</h1>
<form action="/add" method="POST">
<input type="text" name="task" placeholder="New Task name" required>
<button type="submit">Add Task</button>
</form>
<ul>
<% [Link](task => { %>
<li>
<%= [Link] %>
<a href="/complete/<%= task._id %>">Complete</a>
<form action="/complete/<%= [Link] %>" method="POST";
style="display:inline;">
<button type="submit">
<% if ([Link]) { %> ☐
<% } else { %> ☐ <% } %>
</button>
</form>
todo-app/public/[Link]:
body {
font-family: Arial, sans-serif;
width: 50%;
margin: auto;
padding-top: 40px;
h1 {
text-align: center;
form {
margin-bottom: 20px;
ul {
list-style-type: none;
padding-left: 0;
li {
margin-bottom: 10px;
display: flex;
align-items: center;
}
button {
margin-right: 10px;
todo-app/[Link]:
// [Link]
const express = require('express');
const bodyParser = require('body-parser');
const { v4: uuidv4 } = require('uuid');
// Middleware
[Link]([Link]({ extended: true }));
[Link]([Link]('public'));
[Link]('view engine', 'ejs');
// Routes
[Link]('/', (req, res) => {
[Link]('index', { tasks });
});
todo-app/[Link]:
{
"name": "todo-app",
"version": "1.0.0",
"description": "A simple to-do list app using [Link] and [Link]",
"main": "[Link]",
"scripts": {
"start": "node [Link]"
},
"keywords": [
"todo",
"nodejs",
"express"
],
"author": "Your Name",
"license": "MIT",
"dependencies": {
"body-parser": "^1.20.3",
"ejs": "^3.1.10",
"express": "^4.21.2",
"uuid": "^9.0.1"
},
"type": "commonjs"
}
Output:
To-Do List
Add Task