Node.js is a powerful and versatile open-source runtime environment for executing JavaScript code on the server side. It enables developers to build scalable network applications with ease.
Node.js utilizes an asynchronous, non-blocking I/O model, which helps in building highly scalable applications.
const fs = require("fs");
// Non-blocking asynchronous read
fs.readFile("example.txt", "utf8", (err, data) => {
if (err) throw err;
console.log(data);
});
console.log("This will log before the file content.");
The event loop is a core feature of Node.js that manages and dispatches events or messages. It allows Node.js to perform non-blocking operations.
const EventEmitter = require("events");
const myEmitter = new EventEmitter();
myEmitter.on("event", () => {
console.log("An event occurred!");
});
myEmitter.emit("event");
NPM is the default package manager for Node.js, which hosts thousands of libraries and tools for Node.js development.
Install a package:
npm install <package-name>
Install a package globally:
npm install -g <package-name>
Uninstall a package:
npm uninstall <package-name>
Update packages:
npm update
Node.js uses modules to organize code into reusable components. There are built-in modules, third-party modules, and custom modules.
Built-in Module Example:
const http = require("http");
http
.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello World\n");
})
.listen(8080);
Custom Module Example:
math.js
:
module.exports.add = (a, b) => a + b;
app.js
:
const math = require("./math");
console.log(math.add(2, 3)); // 5
Download and install Node.js from the official website. The installation includes NPM.
Check the installed versions of Node.js and NPM:
node -v
npm -v
Create a file named app.js
with the following content:
console.log("Hello, Node.js!");
Run the application:
node app.js
Create a file named server.js
with the following content:
const http = require("http");
const hostname = "127.0.0.1";
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
res.end("Hello World\n");
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Run the server:
node server.js
Visit http://127.0.0.1:3000/
in your web browser to see “Hello World”.
Express.js is a popular web framework for Node.js, designed for building web applications and APIs.
Install Express:
npm install express
Basic Express App:
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.listen(3000, () => {
console.log("App is listening on port 3000!");
});
Promises and async/await are modern JavaScript features for handling asynchronous operations.
Promise Example:
const fs = require("fs").promises;
fs.readFile("example.txt", "utf8")
.then((data) => console.log(data))
.catch((err) => console.error(err));
Async/Await Example:
const fs = require("fs").promises;
async function readFile() {
try {
const data = await fs.readFile("example.txt", "utf8");
console.log(data);
} catch (err) {
console.error(err);
}
}
readFile();