Node.js is a runtime environment that allows you to execute JavaScript on the server side. It's primarily used to build fast and scalable network applications. In this tutorial, we'll be covering several aspects of Node.js including its setup, creating a server, utilizing npm, creating routes, and connecting to databases.
Node.js is built on the V8 JavaScript runtime and helps in building scalable network applications. It uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications.
Node.js enables you to write server-side applications using JavaScript. For example, to print "Hello, World!" with Node.js, you write:
console.log("Hello, World!");
You can install Node.js by downloading the installer from the [official Node.js website](https://nodejs.org/) or using a package manager like `brew` on MacOS or `apt` on Ubuntu.
Using Homebrew on MacOS
brew install node
Using apt on Ubuntu
sudo apt-get update
sudo apt-get install nodejs npm
Node.js can be used to create a simple HTTP server that can serve content to users.
To create a simple server that returns "Hello, World!" whenever accessed:
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
`npm` is the default package manager for Node.js. It allows you to install, share, and manage dependencies (libraries and tools) in your projects.
To install the `express` package using npm:
npm install express
Express is a minimal and flexible Node.js web application framework that provides robust features for web and mobile applications.
Create a simple Express app:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => res.send('Hello World!'));
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`));
Routes define the endpoints that your application will respond to.
Creating a route that responds with "Hello, User!" when accessed:
app.get('/user', (req, res) => res.send('Hello, User!'));
Node.js can connect to databases to store and retrieve data. You can use various databases like MongoDB, MySQL, etc.
Connecting to a MongoDB database using the `mongoose` package:
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));
Middlewares are functions that have access to the request object, the response object, and the next function in the application’s request-response cycle.
Creating a middleware to log requests:
app.use((req, res, next) => {
console.log('Request URL:', req.originalUrl);
next();
});
Node.js uses callbacks, promises, and async/await for handling asynchronous operations.
Using `async/await` to handle asynchronous database calls:
app.get('/data', async (req, res) => {
try {
const data = await getDataFromDb();
res.send(data);
} catch (err) {
res.status(500).send('Error occurred');
}
});
Node.js uses an event-driven, non-blocking I/O model through its event loop mechanism, which enables handling multiple operations without multiple threads or processes, thus, optimizing performance.
const fs = require('fs');
fs.readFile('/file.txt', 'utf-8', (err, data) => {
if (err) throw err;
console.log(data);
});
console.log('Reading file...');
In this example, `readFile` is non-blocking. The program doesn’t wait for the file reading to finish and immediately executes the next line, logging 'Reading file...' to the console.
Node.js has a simple module system where each file is its module. You can export functionalities from one module and import them into another using `require()`.
Creating and using modules:
// math.js
exports.add = (a, b) => a + b;
// app.js
const math = require('./math');
console.log(math.add(1, 2)); // 3
Error handling is crucial for creating robust applications. In Node.js, you can handle errors using callbacks, promises, or async/await.
Handling errors using async/await:
app.get('/error', async (req, res, next) => {
try {
throw new Error('Something went wrong!');
} catch (err) {
next(err);
}
});
Testing is essential for ensuring the correctness of the code. You can use libraries like `mocha` and `chai` for testing Node.js applications.
const { expect } = require('chai');
describe('Math Operations', () => {
it('should add two numbers correctly', () => {
const result = 1 + 2;
expect(result).to.equal(3);
});
});
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