Node.js User Manual

Getting Started

Basic Concepts

Node.js is built on Chrome's V8 JavaScript engine and provides an event-driven, non-blocking I/O model that makes it lightweight and efficient for data-intensive real-time applications.

Event Loop

The Node.js event loop is the core of its concurrency model. Unlike traditional thread-based models, Node.js uses a single-threaded event loop that handles asynchronous operations through callbacks, promises, or async/await.

Non-blocking I/O

Most Node.js operations are non-blocking, meaning they don't halt program execution while waiting for I/O operations to complete. Instead, they use callbacks to handle results when ready.

Hello World Application

Create your first Node.js application with this simple HTTP server:

// server.js
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 it with: node server.js

Core Modules

Node.js comes with a rich set of built-in modules that provide essential functionality without requiring external dependencies.

File System (fs)

Handle file operations synchronously or asynchronously:

const fs = require('fs');

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

// Synchronous read (blocks execution)
try {
  const data = fs.readFileSync('/path/to/file.txt', 'utf8');
  console.log(data);
} catch (err) {
  console.error(err);
}

// Write file
fs.writeFile('/path/to/output.txt', 'Hello Node.js!', (err) => {
  if (err) throw err;
  console.log('File written successfully');
});

HTTP Server

Create web servers and make HTTP requests:

const http = require('http');
const https = require('https');

// Create HTTP server
const server = http.createServer((req, res) => {
  // Handle request
});

// Make HTTP request
const req = http.request('http://example.com', (res) => {
  let data = '';
  res.on('data', (chunk) => {
    data += chunk;
  });
  res.on('end', () => {
    console.log(data);
  });
});
req.end();

Path Utilities

Handle file paths in a cross-platform way:

const path = require('path');

// Join paths
const fullPath = path.join('/home', 'user', 'documents', 'file.txt');

// Get directory name
const dir = path.dirname('/home/user/documents/file.txt');

// Get file extension
const ext = path.extname('file.txt'); // '.txt'

// Resolve absolute path
const absPath = path.resolve('./relative/path');

Events

Work with the EventEmitter class for custom events:

const EventEmitter = require('events');

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();

myEmitter.on('event', () => {
  console.log('An event occurred!');
});

myEmitter.emit('event');

Package Management with npm

npm (Node Package Manager) is the default package manager for Node.js and the largest software registry in the world.

Basic Commands

# Initialize a new project
npm init

# Install packages
npm install express           # Add to dependencies
npm install --save-dev jest   # Add to devDependencies
npm install -g nodemon        # Install globally

# Run scripts defined in package.json
npm start
npm test
npm run build

# Update packages
npm update
npm outdated

# Remove packages
npm uninstall express

package.json Structure

{
  "name": "my-app",
  "version": "1.0.0",
  "description": "A sample Node.js application",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "test": "jest",
    "build": "webpack"
  },
  "dependencies": {
    "express": "^4.18.0"
  },
  "devDependencies": {
    "jest": "^29.0.0"
  },
  "engines": {
    "node": ">=18.0.0"
  }
}

Error Handling

Proper error handling is crucial in Node.js applications due to its asynchronous nature.

Callback-based Error Handling

fs.readFile('file.txt', (err, data) => {
  if (err) {
    console.error('Error reading file:', err);
    return;
  }
  console.log('File content:', data);
});

Promise-based Error Handling

fs.promises.readFile('file.txt')
  .then(data => {
    console.log('File content:', data);
  })
  .catch(err => {
    console.error('Error reading file:', err);
  });

Async/Await Error Handling

async function readFile() {
  try {
    const data = await fs.promises.readFile('file.txt');
    console.log('File content:', data);
  } catch (err) {
    console.error('Error reading file:', err);
  }
}

Performance Optimization

Clustering

Utilize multiple CPU cores with the cluster module:

const cluster = require('cluster');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  console.log(`Master ${process.pid} is running`);
  
  // Fork workers
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
  
  cluster.on('exit', (worker, code, signal) => {
    console.log(`Worker ${worker.process.pid} died`);
  });
} else {
  // Workers share TCP connection
  const http = require('http');
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end('Hello World\n');
  }).listen(8000);
  
  console.log(`Worker ${process.pid} started`);
}

Memory Management

  • Avoid memory leaks by properly cleaning up event listeners
  • Use streams for processing large files instead of loading everything into memory
  • Monitor memory usage with process.memoryUsage()

Caching

Implement caching strategies to improve performance:

const cache = new Map();

function expensiveOperation(key) {
  if (cache.has(key)) {
    return cache.get(key);
  }
  
  const result = performExpensiveCalculation(key);
  cache.set(key, result);
  return result;
}

Debugging and Profiling

Built-in Debugger

Use Node.js's built-in inspector:

# Start application with inspector
node --inspect app.js

# Connect Chrome DevTools to chrome://inspect

Logging

Implement proper logging for production applications:

const winston = require('winston');

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

if (process.env.NODE_ENV !== 'production') {
  logger.add(new winston.transports.Console({
    format: winston.format.simple()
  }));
}

Performance Monitoring

Use built-in performance hooks:

const { PerformanceObserver, performance } = require('perf_hooks');

const obs = new PerformanceObserver((items) => {
  console.log(items.getEntries());
});

obs.observe({ entryTypes: ['measure'] });

performance.mark('start');
// Your code here
performance.mark('end');
performance.measure('My Operation', 'start', 'end');

Security Best Practices

Input Validation

Always validate and sanitize user input:

const validator = require('validator');

if (!validator.isEmail(userInput)) {
  throw new Error('Invalid email address');
}

Environment Variables

Store sensitive information in environment variables:

// Never hardcode secrets
const dbPassword = process.env.DB_PASSWORD;
const apiKey = process.env.API_KEY;

Dependency Security

Regularly audit dependencies for vulnerabilities:

# Check for known vulnerabilities
npm audit

# Automatically fix fixable issues
npm audit fix

Rate Limiting

Implement rate limiting to prevent abuse:

const rateLimit = require('express-rate-limit');

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100 // limit each IP to 100 requests per windowMs
});

app.use(limiter);

Deployment Considerations

Process Management

Use process managers like PM2 for production deployments:

# Install PM2 globally
npm install -g pm2

# Start application
pm2 start app.js

# Monitor processes
pm2 monit

# Set up startup script
pm2 startup

Environment Configuration

Use different configurations for different environments:

// config.js
const config = {
  development: {
    port: 3000,
    databaseUrl: 'mongodb://localhost:27017/myapp_dev'
  },
  production: {
    port: process.env.PORT || 8080,
    databaseUrl: process.env.DATABASE_URL
  }
};

module.exports = config[process.env.NODE_ENV || 'development'];

Health Checks

Implement health check endpoints:

app.get('/health', (req, res) => {
  // Check database connection, external services, etc.
  const health = {
    uptime: process.uptime(),
    message: 'OK',
    timestamp: Date.now()
  };
  res.json(health);
});