BelajarKoding Logobelajarkoding

Platform belajar web development Indonesia. Artikel, cheat sheets, roadmap, dan code challenges untuk developer Indonesia.

Navigasi

  • Artikel
  • Cheat Sheets
  • Roadmap
  • Challenges
  • Pricing
  • Search

Produk Lain

  • JagoHermes
  • KelasClaude
  • KilatKoding
  • BelajarVibeCoding
  • JualanKoding

Support

  • Privacy Policy
  • Terms of Service
  • Email

© 2026 BelajarKoding. All rights reserved.

Galih PratamaBagian dari ekosistem Galih Pratama
belajarkoding LogobyGalih Pratama
RoadmapArtikelCheat SheetsChallengesUpgrade
belajarkoding LogobyGalih Pratama
RoadmapArtikelCheat SheetsChallengesUpgrade
belajarkoding LogobyGalih Pratama
RoadmapArtikelCheat SheetsChallengesUpgrade

Daftar Isi

Installation & SetupModule SystemsCommonJS (require)ES Modules (import)Built-in Modulesfs (File System)pathhttp/httpsosprocessutileventsbufferstreamAsync PatternsCallbacksPromisesAsync/Awaitnpm Commandspackage.json ScriptsEnvironment VariablesError HandlingPattern UmumExpress ServerFile UploadReading JSON FilesFetch with RetryDebuggingPerformance TipsCommon GlobalsUseful Third-Party Packages
Node.jsJavaScriptBackend

Node.js Cheat Sheet

Referensi cepat Node.js runtime. Built-in modules, async patterns, npm commands, dan essential concepts. Must-have buat backend developer.

JavaScript12 min read2.279 kata
Silakan login atau daftar untuk membaca cheat sheet ini.

#Installation & Setup

Cara menginstall dan menjalankan Node.js serta konfigurasi dasar untuk development.

bash
# 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+)

#Module Systems

Sistem modul untuk mengorganisir dan menggunakan kode dalam aplikasi Node.js.

#CommonJS (require)

Sistem modul tradisional menggunakan require() dan module.exports.

javascript
// 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');

#ES Modules (import)

Sistem modul modern menggunakan import dan export syntax.

javascript
// 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');

#Built-in Modules

Modul-modul bawaan Node.js untuk berbagai fungsi seperti file system, networking, dll.

#fs (File System)

Modul untuk berinteraksi dengan file system, membaca dan menulis file.

javascript
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');

#path

Modul untuk memanipulasi dan bekerja dengan path file dan direktori.

javascript
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 Windows

#http/https

Modul untuk membuat HTTP/HTTPS server dan melakukan HTTP requests.

javascript
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();

#os

Modul untuk mendapatkan informasi tentang sistem operasi dan hardware.

javascript
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'

#process

Modul untuk mengakses informasi tentang proses Node.js yang sedang berjalan.

javascript
// 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 }

#util

Modul utility dengan berbagai fungsi helper untuk development.

javascript
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/);          // true

#events

javascript
const 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);
});

#buffer

javascript
// 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)                 // true

#stream

javascript
const 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'));

#Async Patterns

Pola-pola untuk menangani operasi asynchronous dalam Node.js.

#Callbacks

Pola callback tradisional untuk menangani operasi asynchronous.

javascript
fs.readFile('file.txt', 'utf8', (err, data) => {
 if (err) {
  console.error(err);
  return;
 }
 console.log(data);
});

#Promises

Modern approach untuk menangani operasi asynchronous dengan Promise.

javascript
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));

#Async/Await

Sintaks modern untuk menulis kode asynchronous yang lebih readable.

javascript
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');

#npm Commands

Perintah-perintah npm untuk mengelola packages dan proyek Node.js.

bash
# 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 --force

#package.json Scripts

Konfigurasi scripts dalam package.json untuk automation tasks.

json
{
 "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"
 }
}

#Environment Variables

Cara menggunakan environment variables untuk konfigurasi aplikasi.

javascript
// .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
}

#Error Handling

Teknik menangani error dalam aplikasi Node.js dengan berbagai pola.

javascript
// 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);
});

#Pattern Umum

Pola-pola umum yang sering digunakan dalam development Node.js.

#Express Server

Contoh setup server Express.js dengan middleware dan routes.

javascript
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}`);
});

#File Upload

javascript
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;
}

#Reading JSON Files

javascript
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);
}

#Fetch with Retry

javascript
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)));
  }
 }
}

#Debugging

Teknik debugging untuk troubleshooting aplikasi Node.js.

javascript
// 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://inspect

#Performance Tips

Tips optimasi performa untuk aplikasi Node.js yang scalable.

javascript
// 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');
}

#Common Globals

javascript
__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()

#Useful Third-Party Packages

bash
# 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     # TypeScript

Baca Cheat Sheet Lengkap

Login atau daftar akun gratis untuk membaca cheat sheet ini.

LoginDaftar Gratis
Share: