Jump to content

Featured Replies

Posted

You are reading Part 39 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 6]

Introduction

JavaScript 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.js

console.log("Hello from Node.js!");

To run the script:

node script.js

2. Setting Up a Node.js Server

A basic Node.js server can be created using the built-in http module.

Example: Simple HTTP Server

const 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 Loop

Node.js uses an event-driven architecture where callbacks are managed by an event loop.

Example: Asynchronous vs. Synchronous Execution

console.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.js

Node.js allows direct interaction with the file system using the fs module.

Example: Reading a File

const fs = require("fs");

fs.readFile("file.txt", "utf8", (err, data) => {
    if (err) throw err;
    console.log("File Contents:", data);
});

Example: Writing to a File

fs.writeFile("output.txt", "Hello, Node.js!", (err) => {
    if (err) throw err;
    console.log("File written successfully");
});

5. Using Express.js for Backend Development

Express.js is a popular framework for building REST APIs with Node.js.

Example: Simple Express Server

const 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 MongoDB

const 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 Data

const 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 WebSockets

Node.js enables real-time applications using WebSockets.

Example: WebSocket Server with Socket.io

const 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]

  • Views 51
  • Created
  • Last Reply

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

Important Information

Terms of Use Privacy Policy Guidelines We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.