Node.js Documentation
Prerequisites
- Basic JavaScript knowledge
- Node.js LTS version installed
- Familiarity with command-line tools
Introduction
Node.js is a JavaScript runtime built on Chrome's V8 engine, designed for building fast and scalable network applications.
Setup & Installation
Install via the official installer or package manager:
# macOS with Homebrew brew install node # Windows installer from nodejs.org
Modules & Package Management
Node.js uses CommonJS modules by default. Use require()
or ES Modules with import/export
:
// CommonJS const fs = require('fs') // ES Module import fs from 'fs';
Manage packages with npm or pnpm:
npm init npm install express --save
Event Loop & Asynchronous I/O
The event loop handles asynchronous operations. Use callbacks, promises, or async/await:
setTimeout(() => console.log('tick'), 1000); async function read() { const data = await fs.promises.readFile('file.txt'); }
File System
Interact with the file system using the fs
module:
import { promises as fs } from 'fs'; async function save() { await fs.writeFile('data.json', JSON.stringify(obj)); }
Networking
Create HTTP servers:
import http from 'http'; http.createServer((req, res) => { res.end('Hello World'); }).listen(3000);
Popular Frameworks
- Express.js
- Koa.js
- Fastify
Best Practices
- Handle errors gracefully.
- Avoid blocking the event loop.
- Use environment variables for configuration.