You are reading Part 39 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 6] IntroductionJavaScript is traditionally known as a client-side language, but with Node.js, it can also be used for backend development. Node.js is a JavaScript runtime environment that allows developers to run JavaScript on the server, enabling high-performance applications, APIs, and real-time communication. 1. What is Node.js?Node.js is a server-side runtime built on Google Chrome’s V8 JavaScript engine. It enables non-blocking, event-driven programming, making it highly efficient for I/O-intensive tasks. Key Features of Node.js:Asynchronous & Non-blocking – Handles multiple requests concurrently. Single-threaded Event Loop – Uses an event-driven architecture for efficiency. Built-in Modules – Includes modules like fs, http, and crypto. Package Management with NPM – Provides access to thousands of libraries. Example: Running JavaScript in Node.jsconsole.log("Hello from Node.js!");
To run the script: node script.js
2. Setting Up a Node.js ServerA basic Node.js server can be created using the built-in http module. Example: Simple HTTP Serverconst http = require("http");
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello, Node.js Server!");
});
server.listen(3000, () => console.log("Server running on http://localhost:3000"));
Runs a server on port 3000. Responds with "Hello, Node.js Server!". 3. Understanding the Node.js Event LoopNode.js uses an event-driven architecture where callbacks are managed by an event loop. Example: Asynchronous vs. Synchronous Executionconsole.log("Start");
setTimeout(() => console.log("Timeout callback"), 1000);
console.log("End");
Output: Start
End
Timeout callback (after 1 second)
Synchronous code runs first. Asynchronous tasks are pushed to the event loop and executed later. 4. File System Operations in Node.jsNode.js allows direct interaction with the file system using the fs module. Example: Reading a Fileconst fs = require("fs");
fs.readFile("file.txt", "utf8", (err, data) => {
if (err) throw err;
console.log("File Contents:", data);
});
Example: Writing to a Filefs.writeFile("output.txt", "Hello, Node.js!", (err) => {
if (err) throw err;
console.log("File written successfully");
});
5. Using Express.js for Backend DevelopmentExpress.js is a popular framework for building REST APIs with Node.js. Example: Simple Express Serverconst express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("Hello from Express!");
});
app.listen(3000, () => console.log("Express server running on http://localhost:3000"));
Handles HTTP requests using app.get(). Runs on port 3000. 6. Connecting Node.js to a Database (MongoDB)Node.js can connect to databases like MongoDB using libraries like Mongoose. Example: Connecting to MongoDBconst mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/testdb", { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("Connected to MongoDB"))
.catch(err => console.error("MongoDB Connection Error:", err));
Example: Defining a Schema and Saving Dataconst UserSchema = new mongoose.Schema({ name: String, age: Number });
const User = mongoose.model("User", UserSchema);
const newUser = new User({ name: "Alice", age: 30 });
newUser.save().then(() => console.log("User saved"));
7. Real-Time Communication with WebSocketsNode.js enables real-time applications using WebSockets. Example: WebSocket Server with Socket.ioconst io = require("socket.io")(3000);
io.on("connection", socket => {
console.log("New client connected");
socket.on("message", msg => console.log("Message received:", msg));
});
8. When to Use Node.js?Use Case Best Choice? REST APIs ✅ Yes Real-time Chat Apps ✅ Yes CPU-Intensive Tasks ❌ No (Use a compiled language like C++) File System Operations ✅ Yes Machine Learning ❌ No (Python is better) You are reading Part 39 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 6]