Node.js Documentation

JavaScript runtime built on Chrome's V8 JavaScript engine - Build scalable network applications

Introduction to Node.js

Node.js is an open-source, cross-platform JavaScript runtime environment that executes JavaScript code outside a web browser. It allows developers to use JavaScript to write command line tools and for server-side scripting.

Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications.

Setup & Installation

Installing Node.js

Download and install Node.js from the official website: https://nodejs.org

Verify Installation

# Check Node.js version
$ node -v

# Check npm version
$ npm -v

Create Your First Node.js Application

# Create a file named app.js
console.log("Hello, Node.js!");

# Run the application
$ node app.js

Node.js REPL

The REPL (Read-Eval-Print Loop) is an interactive shell that processes Node.js expressions.

$ node
> 5 + 3
8
> "Hello" + " World"
"Hello World"
> .exit # Exit REPL

Modules & npm

Core Modules

Node.js has a set of built-in modules that you can use without any installation.

// Import a core module
const fs = require("fs");
const http = require("http");
const path = require("path");

Creating Your Own Modules

// In math.js
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;

module.exports = { add, subtract };

// In app.js
const math = require("./math.js");
console.log(math.add(5, 3));

npm (Node Package Manager)

npm is the default package manager for Node.js, used to install, share, and manage dependencies.

# Initialize a new project
$ npm init

# Install a package
$ npm install express

# Install a package globally
$ npm install -g nodemon

# List installed packages
$ npm list

# Update packages
$ npm update

# Uninstall a package
$ npm uninstall express

package.json

The package.json file is the heart of any Node.js project. It contains metadata about the project and manages the project's dependencies.

{
  "name": "my-app",
  "version": "1.0.0",
  "description": "My Node.js application",
  "main": "app.js",
  "scripts": {
    "start": "node app.js",
    "dev": "nodemon app.js"
  },
  "dependencies": {
    "express": "^4.18.2"
  },
  "devDependencies": {
    "nodemon": "^3.0.1"
  }
}

File System Module

The fs module provides an API for interacting with the file system in a manner closely modeled around standard POSIX functions.

Reading Files

const fs = require("fs");

// Synchronous read
const data = fs.readFileSync("file.txt", "utf8");
console.log(data);

// Asynchronous read
fs.readFile("file.txt", "utf8", (err, data) => {
  if (err) throw err;
  console.log(data);
});

Writing Files

// Synchronous write
fs.writeFileSync("file.txt", "Hello, World!");

// Asynchronous write
fs.writeFile("file.txt", "Hello, World!", (err) => {
  if (err) throw err;
  console.log("File saved!");
});

File System Operations

// Check if file exists
fs.existsSync("file.txt");

// Get file info
const stats = fs.statSync("file.txt");
console.log(stats.size);

// Create directory
fs.mkdirSync("new-directory");

// Remove file
fs.unlinkSync("file.txt");

HTTP Module

The http module allows Node.js to transfer data over the Hyper Text Transfer Protocol (HTTP).

Create a Simple HTTP Server

const http = require("http");

const server = http.createServer((req, res) => {
  res.writeHead(200, {
    "Content-Type": "text/plain"
  });
  res.end("Hello, World!\n");
});

server.listen(3000, "localhost", () => {
  console.log("Server running at http://localhost:3000/");
});

Making HTTP Requests

const http = require("http");

const options = {
  "hostname": "jsonplaceholder.typicode.com",
  "path": "/posts/1",
  "method": "GET"
};

const req = http.request(options, (res) => {
  let data = "";
  
  res.on("data", (chunk) => {
    data += chunk;
  });
  
  res.on("end", () => {
    console.log(data);
  });
});

req.end();

Express.js

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

Install Express

$ npm install express

Basic Express Application

const express = require("express");
const app = express();
const port = 3000;

// Middleware
app.use(express.json());

// Routes
app.get("/", (req, res) => {
  res.send("Hello, Express!");
});

app.get("/api/users", (req, res) => {
  res.json([{
    "name": "John",
    "age": 30
  }, {
    "name": "Jane",
    "age": 25
  }]);
});

// Start server
app.listen(port, () => {
  console.log(`Server running on port ${port`);
});

Route Parameters

app.get("/users/:id", (req, res) => {
  const userId = req.params.id;
  res.send(`User ID: ${userId`);
});

app.get("/search", (req, res) => {
  const query = req.query.q;
  res.send(`Search query: ${query`);
});

Middleware

// Custom middleware
app.use((req, res, next) => {
  console.log("Request received:", req.method, req.url);
  next();
});

// Error handling middleware
app.use((err, req, res, next) => {
  res.status(500).send("Something broke!");
});

Asynchronous Programming

Node.js is designed to be non-blocking, making it ideal for handling I/O operations asynchronously.

Callbacks

const fs = require("fs");

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

Promises

const fs = require("fs/promises");

async function readFile() {
  try {
    const data = await fs.readFile("file.txt", "utf8");
    console.log(data);
  } catch (err) {
    console.error(err);
  }
}

readFile();

Async/Await

function fetchData() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("Data fetched");
    }, 1000);
  });
}

async function main() {
  const data = await fetchData();
  console.log(data);
}

main();

Event Emitter

const EventEmitter = require("events");

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();

// Listen for event
myEmitter.on("event", () => {
  console.log("Event occurred!");
});

// Emit event
myEmitter.emit("event");

Database Integration

Node.js can connect to various databases using different libraries and drivers.

MongoDB with Mongoose

// Install mongoose
$ npm install mongoose

const mongoose = require("mongoose");

// Connect to MongoDB
mongoose.connect("mongodb://localhost:27017/mydatabase");

// Define a schema
const userSchema = new mongoose.Schema({
  "name": String,
  "email": String,
  "age": Number
});

// Create a model
const User = mongoose.model("User", userSchema);

// Create a new user
const newUser = new User({
  "name": "John Doe",
  "email": "john@example.com",
  "age": 30
});

newUser.save()
  .then(() => console.log("User saved!"))
  .catch(err => console.error(err));

MySQL with mysql2

// Install mysql2
$ npm install mysql2

const mysql = require("mysql2/promise");

// Create connection pool
const pool = mysql.createPool({
  "host": "localhost",
  "user": "root",
  "password": "password",
  "database": "mydatabase"
});

// Query the database
async function getUsers() {
  const [rows] = await pool.query("SELECT * FROM users");
  return rows;
}

SQLite with sqlite3

// Install sqlite3
$ npm install sqlite3

const sqlite3 = require("sqlite3");
const db = new sqlite3.Database("./mydatabase.db");

db.serialize(() => {
  db.run("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)");
  
  db.run("INSERT INTO users (name) VALUES (?)", ["John Doe"], function(err) {
    if (err) return console.error(err);
    console.log("User inserted!");
  });
  
  db.each("SELECT * FROM users", (err, row) => {
    console.log(row);
  });
});

db.close();

Practical Examples

Simple Web Server

const http = require("http");
const url = require("url");

const server = http.createServer((req, res) => {
  const pathname = url.parse(req.url).pathname;
  
  if (pathname === "/") {
    res.writeHead(200, {
      "Content-Type": "text/plain"
    });
    res.end("Hello, Node.js Server!");
  } else if (pathname === "/about") {
    res.writeHead(200, {
      "Content-Type": "text/plain"
    });
    res.end("About Page");
  } else {
    res.writeHead(404);
    res.end("Page not found");
  }
});

server.listen(3000, () => {
  console.log("Server running on port 3000");
});

REST API with Express

const express = require("express");
const app = express();
const port = 3000;

app.use(express.json());

// In-memory database
let users = [
  {
    "id": 1,
    "name": "John Doe",
    "email": "john@example.com"
  },
  {
    "id": 2,
    "name": "Jane Smith",
    "email": "jane@example.com"
  }
];

// GET all users
app.get("/api/users", (req, res) => {
  res.json(users);
});

// GET single user
app.get("/api/users/:id", (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id);
  if (user) {
    res.json(user);
  } else {
    res.status(404).json({
      "message": "User not found"
    });
  }
});

// POST create user
app.post("/api/users", (req, res) => {
  const newUser = {
    "id": users.length + 1,
    "name": req.body.name,
    "email": req.body.email
  };
  users.push(newUser);
  res.status(201).json(newUser);
});

app.listen(port, () => {
  console.log(`Server running on port ${port`);
});

File Upload Server

const express = require("express");
const multer = require("multer");
const path = require("path");

const app = express();
const upload = multer({
  "dest": "uploads/"
});

app.post("/upload", upload.single("file"), (req, res) => {
  res.send("File uploaded successfully!");
});

app.listen(3000, () => {
  console.log("File upload server running on port 3000");
});