Node.js

Table of Contents

Introduction

Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It enables running JavaScript on the server side, allowing for building scalable network applications using an event-driven, non-blocking I/O model.

Key Features:

Core Concepts

Event Loop


// Event Loop Example
const fs = require('fs');

console.log('Start');

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

// Immediate execution
console.log('End');

// Output:
// Start
// End
// File read
    

Node.js Modules

Core Modules:


// File System Operations
const fs = require('fs');

// HTTP Server
const http = require('http');

// Path Manipulation
const path = require('path');

// Operating System
const os = require('os');

// Events
const EventEmitter = require('events');
        

Creating Custom Modules


// math.js
module.exports = {
    add: (a, b) => a + b,
    subtract: (a, b) => a - b,
    multiply: (a, b) => a * b
};

// main.js
const math = require('./math');
console.log(math.add(5, 3));  // Output: 8
    

NPM (Node Package Manager)

Package Management:


// Initialize new project
npm init

// Install package
npm install express

// Install dev dependency
npm install --save-dev nodemon

// Package.json example
{
    "name": "my-node-app",
    "version": "1.0.0",
    "dependencies": {
        "express": "^4.17.1"
    },
    "devDependencies": {
        "nodemon": "^2.0.7"
    }
}
        

Asynchronous Programming

Promises and Async/Await


// Promise-based code
function readFilePromise(path) {
    return new Promise((resolve, reject) => {
        fs.readFile(path, 'utf8', (err, data) => {
            if (err) reject(err);
            resolve(data);
        });
    });
}

// Async/Await usage
async function processFile() {
    try {
        const data = await readFilePromise('file.txt');
        console.log(data);
    } catch (error) {
        console.error(error);
    }
}
    

Web Server Development

Basic HTTP Server:


const http = require('http');

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello World\n');
});

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

Express.js Web Application


const express = require('express');
const app = express();

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

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

app.post('/api/data', (req, res) => {
    const data = req.body;
    // Process data
    res.json({ success: true });
});

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

Best Practices

Development Guidelines:

Error Handling Example


// Global error handler
process.on('uncaughtException', (error) => {
    console.error('Uncaught Exception:', error);
    // Clean up and exit
    process.exit(1);
});

// Promise rejection handler
process.on('unhandledRejection', (reason, promise) => {
    console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});

// Express error handling middleware
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});
    

Environment Configuration


// .env file
PORT=3000
DB_URL=mongodb://localhost:27017
API_KEY=your_api_key

// Usage with dotenv
require('dotenv').config();

const app = express();
app.listen(process.env.PORT, () => {
    console.log(`Server running on port ${process.env.PORT}`);
});
    

Related Resources