Node.js is an open-source runtime environment that allows you to execute JavaScript on the server-side. It’s built on the V8 JavaScript runtime and helps in building scalable network applications.
Before diving into coding examples, download and install Node.js from the [official website](https://nodejs.org/). Once installed, you can check the version using the following commands in your terminal or command prompt:
node -v
npm -v
Let’s start by creating a basic server. Create a new file named `app.js` and add the following code:
const http = require('http');
const server = http.createServer((req, res) => {
res.end('Hello, World!');
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
Run the server with:
node app.js
Visit `http://localhost:3000` in your browser, and you should see “Hello, World!”.
Node.js utilizes modules, which are akin to JavaScript libraries. Modules are a set of functions that you want to include in your application.
Create a file named `math.js`:
exports.add = (x, y) => x + y;
exports.subtract = (x, y) => x - y;
In `app.js`:
const math = require('./math');
console.log(math.add(2, 3)); // 5
console.log(math.subtract(7, 4)); // 3
Node.js operates on a single-threaded event loop, using non-blocking I/O calls, allowing it to support thousands of concurrent connections. Here’s an example to demonstrate the non-blocking nature:
const fs = require('fs');
console.log('Start reading a file...');
fs.readFile('path-to-file', 'utf-8', (err, content) => {
if (err) {
console.log('Error happened during reading the file');
return console.log(err);
}
console.log(content);
});
console.log('End of the script');
This will print 'Start reading a file...', 'End of the script', and then the content of the file.
Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications.
Install Express using npm:
npm init -y
npm install express
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`);
});
Node.js extensively uses asynchronous programming. Callbacks, Promises, and Async/Await are three ways to handle asynchronous operations.
const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
const readFile = (fileName) => {
return new Promise((resolve, reject) => {
fs.readFile(fileName, 'utf8', (err, data) => {
if (err) reject(err);
resolve(data);
});
});
};
readFile('file.txt').then(data => console.log(data)).catch(err => console.log(err));
const util = require('util');
const readFile = util.promisify(fs.readFile);
const read = async () => {
try {
const data = await readFile('file.txt', 'utf8');
console.log(data);
} catch (err) {
console.log(err);
}
};
read();
In Express, middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle.
app.use((req, res, next) => {
console.log('Time: ', Date.now());
next();
});
app.get('/', (req, res) => {
res.send('Hello, World!');
});
Node.js can connect to databases, and one common database is MongoDB. To connect Node.js with MongoDB, use the Mongoose library.
npm install mongoose
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true, useUnifiedTopology: true})
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Could not connect to MongoDB', err));
Create a model:
const UserSchema = new mongoose.Schema({
name: String,
email: String,
password: String
});
const User = mongoose.model('User', UserSchema);
Create routes:
app.post('/users', async (req, res) => {
let user = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password
});
user = await user.save();
res.send(user);
});
app.get('/users', async (req, res) => {
const users = await User.find();
res.send(users);
});
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here