Last Updated: November 21, 2025
Core Modules
| Module | Purpose |
|---|---|
fs
|
File system operations |
path
|
File path utilities |
http/https
|
HTTP server and client |
os
|
Operating system info |
events
|
Event emitter |
stream
|
Streaming data |
crypto
|
Cryptographic functions |
util
|
Utility functions |
File System (fs)
const fs = require('fs');
// Read file (async)
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
// Read file (sync)
const data = fs.readFileSync('file.txt', 'utf8');
// Write file
fs.writeFile('output.txt', 'Hello', (err) => {
if (err) throw err;
});
// Promises API (modern)
const fs = require('fs').promises;
const data = await fs.readFile('file.txt', 'utf8');
HTTP Server
const http = require('http');
const server = http.createServer((req, res) => {
// Set response headers
res.writeHead(200, { 'Content-Type': 'text/html' });
// Routing
if (req.url === '/') {
res.end('<h1>Home</h1>');
} else if (req.url === '/api') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'API response' }));
} else {
res.writeHead(404);
res.end('Not Found');
}
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});
NPM Commands
npm init
Initialize new project
npm install package
Install package
npm install -g package
Install globally
npm install --save-dev package
Install as dev dependency
npm uninstall package
Remove package
npm update
Update packages
npm run script
Run package.json script
Environment Variables
// Access environment variables
const port = process.env.PORT || 3000;
const dbUrl = process.env.DATABASE_URL;
// Using dotenv package
require('dotenv').config();
const apiKey = process.env.API_KEY;
// .env file format:
// PORT=3000
// DATABASE_URL=mongodb://localhost/mydb
// API_KEY=your_key_here
💡 Pro Tip:
Always use environment variables for sensitive data and configuration!