Referensi cepat Node.js runtime. Built-in modules, async patterns, npm commands, dan essential concepts. Must-have buat backend developer.
Cara menginstall dan menjalankan Node.js serta konfigurasi dasar untuk development.
# Check version
node --version
npm --version
# Run JavaScript file
node index.js
# Start REPL (interactive shell)
node
# Run with flags
node --inspect index.js # Enable debugger
node --watch index.js # Auto-restart on changes (Node 18+)Sistem modul untuk mengorganisir dan menggunakan kode dalam aplikasi Node.js.
Sistem modul tradisional menggunakan require() dan module.exports.
// Export
module.exports = { add, multiply };
module.exports.add = add;
exports.add = add; // Shorthand
// Import
const math = require('./math');
const { add } = require('./math');
// Built-in modules
const fs = require('fs');
const path = require('path');Sistem modul modern menggunakan import dan export syntax.
// package.json
{
"type": "module"
}
// or use .mjs extension
// Export
export function add(a, b) { return a + b; }
export const PI = 3.14;
export default function subtract(a, b) { return a - b; }
// Import
import subtract, { add, PI } from './math.mjs';
import * as math from './math.mjs';
// Dynamic import
const module = await import('./module.mjs');Modul-modul bawaan Node.js untuk berbagai fungsi seperti file system, networking, dll.
Modul untuk berinteraksi dengan file system, membaca dan menulis file.
const fs = require('fs');
// Read file (callback)
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
// Write file
fs.writeFile('file.txt', 'Hello World', (err) => {
if (err) throw err;
});
// Append
fs.appendFile('file.txt', 'More data', (err) => {});
// Delete
fs.unlink('file.txt', (err) => {});
// Promises API (modern)
const fs = require('fs').promises;
await fs.readFile('file.txt', 'utf8');
await fs.writeFile('file.txt', 'Hello');
await fs.appendFile('file.txt', 'data');
await fs.unlink('file.txt');
await fs.mkdir('folder', { recursive: true });
await fs.readdir('folder');
await fs.stat('file.txt');
await fs.rename('old.txt', 'new.txt');
// Sync (avoid in production!)
const data = fs.readFileSync('file.txt', 'utf8');
fs.writeFileSync('file.txt', 'Hello');Modul untuk memanipulasi dan bekerja dengan path file dan direktori.
const path = require('path');
// Join paths
path.join('/home', 'user', 'file.txt'); // /home/user/file.txt
path.join(__dirname, 'uploads', 'image.jpg');
// Resolve absolute path
path.resolve('uploads', 'file.txt'); // /current/dir/uploads/file.txt
// Parse path
path.parse('/home/user/file.txt');
// { root: '/', dir: '/home/user', base: 'file.txt', ext: '.txt', name: 'file' }
// Path parts
path.basename('/home/user/file.txt'); // file.txt
path.dirname('/home/user/file.txt'); // /home/user
path.extname('/home/user/file.txt'); // .txt
// Normalize
path.normalize('/home//user/../user/file.txt'); // /home/user/file.txt
// Relative path
path.relative('/home/user', '/home/user/docs'); // docs
// Check if absolute
path.isAbsolute('/home/user'); // true
path.isAbsolute('user/file.txt'); // false
// Platform-specific separator
path.sep // '/' on Unix, '\\' on Windows
path.delimiter // ':' on Unix, ';' on WindowsModul untuk membuat HTTP/HTTPS server dan melakukan HTTP requests.
const http = require('http');
// Create server
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
// Make request
http.get('http://api.example.com', (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => console.log(data));
});
// HTTPS
const https = require('https');
const options = {
hostname: 'api.example.com',
path: '/data',
method: 'POST',
headers: { 'Content-Type': 'application/json' }
};
const req = https.request(options, (res) => {
console.log('Status:', res.statusCode);
res.on('data', d => process.stdout.write(d));
});
req.write(JSON.stringify({ name: 'John' }));
req.end();Modul untuk mendapatkan informasi tentang sistem operasi dan hardware.
const os = require('os');
os.platform() // 'linux', 'darwin', 'win32'
os.arch() // 'x64', 'arm'
os.cpus() // Array of CPU info
os.cpus().length // Number of CPU cores
os.totalmem() // Total memory (bytes)
os.freemem() // Free memory (bytes)
os.uptime() // System uptime (seconds)
os.hostname() // Hostname
os.homedir() // Home directory path
os.tmpdir() // Temp directory path
os.type() // OS type: 'Linux', 'Darwin', 'Windows_NT'
os.release() // OS release version
os.networkInterfaces() // Network interfaces
os.EOL // End of line: '\n' or '\r\n'Modul untuk mengakses informasi tentang proses Node.js yang sedang berjalan.
// Current directory
process.cwd() // Current working directory
process.chdir('/new/path') // Change directory
// Environment
process.env.NODE_ENV // Environment variables
process.env.PORT
// Arguments
process.argv // Command line arguments
// node app.js arg1 arg2
// ['node', '/path/to/app.js', 'arg1', 'arg2']
// Process info
process.pid // Process ID
process.platform // Platform
process.version // Node version
process.versions // All versions (V8, etc)
// Exit
process.exit(0) // Exit dengan code 0 (success)
process.exit(1) // Exit dengan code 1 (error)
// Events
process.on('exit', code => {
console.log(`Exiting with code ${code}`);
});
process.on('uncaughtException', err => {
console.error('Uncaught Exception:', err);
process.exit(1);
});
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection:', reason);
process.exit(1);
});
// Signals
process.on('SIGTERM', () => {
console.log('SIGTERM received');
server.close(() => process.exit(0));
});
// Memory usage
process.memoryUsage();
// { rss, heapTotal, heapUsed, external, arrayBuffers }Modul utility dengan berbagai fungsi helper untuk development.
const util = require('util');
// Promisify callback-based functions
const fs = require('fs');
const readFile = util.promisify(fs.readFile);
await readFile('file.txt', 'utf8');
// Format strings
util.format('Hello %s', 'World'); // Hello World
util.format('%d + %d = %d', 1, 2, 3); // 1 + 2 = 3
// Inspect objects
util.inspect({ name: 'John', age: 30 });
util.inspect(obj, { depth: null, colors: true });
// Type checking
util.types.isDate(new Date()); // true
util.types.isPromise(Promise.resolve()); // true
util.types.isRegExp(/test/); // trueconst EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
// Listen to events
myEmitter.on('event', (arg1, arg2) => {
console.log('Event fired!', arg1, arg2);
});
// Listen once
myEmitter.once('event', () => {
console.log('Will only run once');
});
// Emit event
myEmitter.emit('event', 'arg1', 'arg2');
// Remove listener
const callback = () => console.log('callback');
myEmitter.on('event', callback);
myEmitter.removeListener('event', callback);
// Remove all listeners
myEmitter.removeAllListeners('event');
// Error handling
myEmitter.on('error', err => {
console.error('Error:', err);
});// Create buffer
const buf1 = Buffer.from('Hello');
const buf2 = Buffer.from([72, 101, 108, 108, 111]); // ASCII codes
const buf3 = Buffer.alloc(10); // 10 bytes, filled with 0
const buf4 = Buffer.allocUnsafe(10); // Faster, not initialized
// Read
buf1.toString() // 'Hello'
buf1.toString('hex') // '48656c6c6f'
buf1.toString('base64') // 'SGVsbG8='
buf1[0] // 72 (ASCII 'H')
// Write
buf3.write('Hello');
// Length
buf1.length // 5 bytes
// Compare
Buffer.compare(buf1, buf2) // 0 (equal), -1, or 1
// Concat
Buffer.concat([buf1, buf2]);
// Check if buffer
Buffer.isBuffer(buf1) // trueconst fs = require('fs');
// Readable stream
const readable = fs.createReadStream('input.txt');
readable.on('data', chunk => {
console.log('Chunk:', chunk);
});
readable.on('end', () => {
console.log('Done reading');
});
readable.on('error', err => {
console.error('Error:', err);
});
// Writable stream
const writable = fs.createWriteStream('output.txt');
writable.write('Hello ');
writable.write('World');
writable.end();
// Pipe (efficient way to transfer data)
fs.createReadStream('input.txt')
.pipe(fs.createWriteStream('output.txt'));
// Transform stream (zlib example)
const zlib = require('zlib');
fs.createReadStream('input.txt')
.pipe(zlib.createGzip())
.pipe(fs.createWriteStream('input.txt.gz'));Pola-pola untuk menangani operasi asynchronous dalam Node.js.
Pola callback tradisional untuk menangani operasi asynchronous.
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});Modern approach untuk menangani operasi asynchronous dengan Promise.
const fs = require('fs').promises;
fs.readFile('file.txt', 'utf8')
.then(data => console.log(data))
.catch(err => console.error(err));
// Promise.all (parallel)
Promise.all([
fs.readFile('file1.txt'),
fs.readFile('file2.txt')
])
.then(([data1, data2]) => console.log(data1, data2))
.catch(err => console.error(err));
// Promise.race (first to finish)
Promise.race([
fetch('api1.com'),
fetch('api2.com')
])
.then(result => console.log(result));
// Promise.allSettled (wait all, even if some fail)
Promise.allSettled([
Promise.resolve('success'),
Promise.reject('error')
])
.then(results => console.log(results));Sintaks modern untuk menulis kode asynchronous yang lebih readable.
async function readFiles() {
try {
const data1 = await fs.readFile('file1.txt', 'utf8');
const data2 = await fs.readFile('file2.txt', 'utf8');
console.log(data1, data2);
} catch (err) {
console.error(err);
}
}
// Parallel with Promise.all
async function readFilesParallel() {
const [data1, data2] = await Promise.all([
fs.readFile('file1.txt', 'utf8'),
fs.readFile('file2.txt', 'utf8')
]);
console.log(data1, data2);
}
// Top-level await (ESM only)
const data = await fs.readFile('file.txt', 'utf8');Perintah-perintah npm untuk mengelola packages dan proyek Node.js.
# Initialize project
npm init
npm init -y # Skip prompts
# Install packages
npm install package-name # Install & add to dependencies
npm install -D package-name # Install to devDependencies
npm install -g package-name # Install globally
npm install # Install all from package.json
# Install specific version
npm install package@1.2.3
npm install package@latest
# Uninstall
npm uninstall package-name
npm uninstall -g package-name
# Update
npm update # Update all
npm update package-name # Update specific
npm outdated # Check outdated packages
# Scripts
npm start # Run "start" script
npm test # Run "test" script
npm run build # Run "build" script
npm run script-name # Run custom script
# Info
npm list # List installed packages
npm list --depth=0 # List top-level only
npm list -g --depth=0 # List global packages
npm view package-name versions # View available versions
npm view package-name # View package info
# Security
npm audit # Check vulnerabilities
npm audit fix # Auto fix vulnerabilities
npm audit fix --force # Force fix (may break things)
# Cache
npm cache clean --force # Clear npm cache
# Publishing
npm login # Login to npm
npm publish # Publish package
npm unpublish package@version --forceKonfigurasi scripts dalam package.json untuk automation tasks.
{
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js",
"build": "webpack",
"test": "jest",
"lint": "eslint .",
"format": "prettier --write .",
"pre-commit": "lint-staged",
"prepare": "husky install"
}
}Cara menggunakan environment variables untuk konfigurasi aplikasi.
// .env file
// PORT=3000
// DB_HOST=localhost
// API_KEY=secret123
// Install dotenv: npm install dotenv
require('dotenv').config();
const port = process.env.PORT || 3000;
const dbHost = process.env.DB_HOST;
const apiKey = process.env.API_KEY;
// Check environment
if (process.env.NODE_ENV === 'production') {
// Production config
} else {
// Development config
}Teknik menangani error dalam aplikasi Node.js dengan berbagai pola.
// Try/catch with async/await
async function getUser(id) {
try {
const user = await db.findUser(id);
return user;
} catch (err) {
console.error('Error getting user:', err);
throw err;
}
}
// Promise catch
fetchData()
.then(data => processData(data))
.catch(err => console.error('Error:', err))
.finally(() => console.log('Done'));
// Callback error handling
fs.readFile('file.txt', (err, data) => {
if (err) {
if (err.code === 'ENOENT') {
console.error('File not found');
} else {
console.error('Error reading file:', err);
}
return;
}
console.log(data);
});
// Process-level error handlers
process.on('uncaughtException', err => {
console.error('Uncaught Exception:', err);
process.exit(1);
});
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection:', reason);
process.exit(1);
});Pola-pola umum yang sering digunakan dalam development Node.js.
Contoh setup server Express.js dengan middleware dan routes.
const express = require('express');
const app = express();
// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));
// Routes
app.get('/', (req, res) => {
res.send('Hello World');
});
app.get('/api/users', async (req, res) => {
try {
const users = await db.getUsers();
res.json(users);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Error handler
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});const fs = require('fs').promises;
const path = require('path');
async function saveFile(filename, data) {
const uploadDir = path.join(__dirname, 'uploads');
// Create directory if not exists
await fs.mkdir(uploadDir, { recursive: true });
const filepath = path.join(uploadDir, filename);
await fs.writeFile(filepath, data);
return filepath;
}const fs = require('fs').promises;
// Read & parse JSON
async function readJSON(filepath) {
const data = await fs.readFile(filepath, 'utf8');
return JSON.parse(data);
}
// Write JSON
async function writeJSON(filepath, data) {
const jsonString = JSON.stringify(data, null, 2);
await fs.writeFile(filepath, jsonString);
}async function fetchWithRetry(url, options = {}, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
const response = await fetch(url, options);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response;
} catch (err) {
if (i === maxRetries - 1) throw err;
await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
}
}
}Teknik debugging untuk troubleshooting aplikasi Node.js.
// console methods
console.log('Log message');
console.error('Error message');
console.warn('Warning');
console.table([{ name: 'John', age: 30 }]);
console.time('timer');
// ... code
console.timeEnd('timer');
// Debugger
debugger; // Breakpoint
// Run with inspector
// node --inspect index.js
// node --inspect-brk index.js // Break on first line
// Chrome DevTools: chrome://inspectTips optimasi performa untuk aplikasi Node.js yang scalable.
// Use async APIs (don't block event loop)
const data = await fs.readFile('file.txt'); // Good
// const data = fs.readFileSync('file.txt'); // Bad
// Stream large files
fs.createReadStream('large-file.txt')
.pipe(res);
// Use Promise.all for parallel operations
const [users, posts] = await Promise.all([
db.getUsers(),
db.getPosts()
]);
// Cache expensive operations
const cache = new Map();
async function getUser(id) {
if (cache.has(id)) return cache.get(id);
const user = await db.findUser(id);
cache.set(id, user);
return user;
}
// Use cluster for multi-core
const cluster = require('cluster');
const os = require('os');
if (cluster.isMaster) {
for (let i = 0; i < os.cpus().length; i++) {
cluster.fork();
}
} else {
require('./app');
}__dirname // Current directory path
__filename // Current file path
__filename // Current file path
global // Global object
console // Console object
process // Process object
Buffer // Buffer class
setTimeout() // Set timeout
setInterval() // Set interval
setImmediate() // Execute on next tick
clearTimeout()
clearInterval()
clearImmediate()# Web frameworks
npm install express # Minimal web framework
npm install fastify # Fast web framework
npm install koa # Modern framework
# Database
npm install mongoose # MongoDB ORM
npm install prisma # Type-safe ORM
npm install pg # PostgreSQL client
# Utilities
npm install lodash # Utility functions
npm install axios # HTTP client
npm install dayjs # Date library
npm install dotenv # Load .env files
npm install validator # String validation
# Dev tools
npm install -D nodemon # Auto-restart on changes
npm install -D eslint # Linter
npm install -D prettier # Code formatter
npm install -D jest # Testing framework
npm install -D typescript # TypeScriptLogin atau daftar akun gratis untuk membaca cheat sheet ini.