NODEJS DOCS

GLOBAL-OBJECTS

global
Description: Objek global Node.js (seperti window di browser).
Example:
console.log(global)
Output: <ref *1> Object [global] ...
globalThis
Description: Referensi standar ke objek global (Node.js & browser).
Example:
globalThis.setTimeout === setTimeout
Output: true
__dirname
Description: Path direktori file saat ini (CommonJS only).
Example:
console.log(__dirname)
Output: /home/user/project/src
__filename
Description: Path lengkap file saat ini (CommonJS only).
Example:
console.log(__filename)
Output: /home/user/project/src/app.js
process
Description: Objek proses Node.js (env, argv, exit, dll).
Example:
console.log(process.pid)
Output: 12345
process.argv
Description: Array argumen command line.
Example:
node app.js arg1 arg2
Output: ['node', 'app.js', 'arg1', 'arg2']
process.env
Description: Environment variables.
Example:
process.env.NODE_ENV
Output: 'production'
process.cwd()
Description: Current working directory.
Example:
process.cwd()
Output: /home/user/project
process.exit(code)
Description: Keluar dari proses dengan kode.
Example:
process.exit(0)
Output: Keluar sukses
process.nextTick(cb)
Description: Jalankan callback di next tick event loop.
Example:
process.nextTick(() => console.log('next'))
Output: next (sebelum I/O)
process.memoryUsage()
Description: Info penggunaan memori.
Example:
process.memoryUsage()
Output: { rss: ..., heapTotal: ..., heapUsed: ... }
process.uptime()
Description: Uptime proses dalam detik.
Example:
process.uptime()
Output: 123.456
process.platform
Description: Platform OS (linux, darwin, win32).
Example:
process.platform
Output: 'linux'
process.version
Description: Versi Node.js.
Example:
process.version
Output: 'v20.10.0'
Buffer
Description: Menangani data biner.
Example:
Buffer.from('hello')
Output: <Buffer 68 65 6c 6c 6f>
URL
Description: Parsing & manipulasi URL (WHATWG API).
Example:
new URL('https://example.com/path?q=1')
Output: URL object
URLSearchParams
Description: Parsing query string.
Example:
new URLSearchParams('q=hello&page=1')
Output: URLSearchParams { 'q' => 'hello', 'page' => '1' }
TextEncoder
Description: Encode string ke Uint8Array.
Example:
new TextEncoder().encode('hi')
Output: Uint8Array [104, 105]
TextDecoder
Description: Decode Uint8Array ke string.
Example:
new TextDecoder().decode(buffer)
Output: 'hi'
setTimeout(cb, delay)
Description: Jalankan callback setelah delay ms.
Example:
setTimeout(() => {}, 1000)
Output: Timeout object
setInterval(cb, delay)
Description: Jalankan callback berulang tiap delay ms.
Example:
setInterval(() => {}, 1000)
Output: Interval object
setImmediate(cb)
Description: Jalankan callback di fase check event loop.
Example:
setImmediate(() => console.log('immediate'))
Output: immediate
clearTimeout(id)
Description: Hentikan timeout.
Example:
clearTimeout(id)
Output: Dibatalkan
clearInterval(id)
Description: Hentikan interval.
Example:
clearInterval(id)
Output: Dibatalkan
clearImmediate(id)
Description: Hentikan immediate.
Example:
clearImmediate(id)
Output: Dibatalkan

FS

fs.readFile(path, cb)
Description: Baca file secara asynchronous.
Example:
fs.readFile('/path/file.txt', 'utf8', (err, data) => {})
Output: Isi file
fs.readFileSync(path)
Description: Baca file secara synchronous.
Example:
const data = fs.readFileSync('/path/file.txt', 'utf8')
Output: Isi file
fs.writeFile(path, data, cb)
Description: Tulis file (overwrite).
Example:
fs.writeFile('/path/file.txt', 'Hello', (err) => {})
Output: File tertulis
fs.writeFileSync(path, data)
Description: Tulis file synchronous.
Example:
fs.writeFileSync('/path/file.txt', 'Hello')
Output: File tertulis
fs.appendFile(path, data, cb)
Description: Tambah data ke akhir file.
Example:
fs.appendFile('/path/file.txt', 'World', (err) => {})
Output: Data ditambahkan
fs.unlink(path, cb)
Description: Hapus file.
Example:
fs.unlink('/path/file.txt', (err) => {})
Output: File dihapus
fs.existsSync(path)
Description: Cek apakah path ada (sync).
Example:
fs.existsSync('/path/file.txt')
Output: true / false
fs.mkdir(path, cb)
Description: Buat folder.
Example:
fs.mkdir('/path/new-folder', (err) => {})
Output: Folder dibuat
fs.mkdirSync(path, { recursive: true })
Description: Buat folder recursive.
Example:
fs.mkdirSync('/a/b/c', { recursive: true })
Output: Semua folder dibuat
fs.rmdir(path, cb)
Description: Hapus folder kosong.
Example:
fs.rmdir('/path/folder', (err) => {})
Output: Folder dihapus
fs.rm(path, { recursive: true }, cb)
Description: Hapus folder beserta isinya (Node 14+).
Example:
fs.rm('/path/folder', { recursive: true, force: true }, (err) => {})
Output: Folder & isi dihapus
fs.readdir(path, cb)
Description: Baca isi folder.
Example:
fs.readdir('/path', (err, files) => {})
Output: ['file1.txt', 'file2.js']
fs.stat(path, cb)
Description: Info file/folder (size, modified, dll).
Example:
fs.stat('/path/file.txt', (err, stats) => {})
Output: Stats { size: 123, ... }
fs.copyFile(src, dest, cb)
Description: Copy file.
Example:
fs.copyFile('src.txt', 'dest.txt', (err) => {})
Output: File dicopy
fs.rename(old, new, cb)
Description: Rename / pindahkan file.
Example:
fs.rename('old.txt', 'new.txt', (err) => {})
Output: File direname
fs.watch(path, cb)
Description: Pantau perubahan file/folder.
Example:
fs.watch('/path', (event, filename) => {})
Output: 'change' 'file.txt'
fs.createReadStream(path)
Description: Stream baca file (untuk file besar).
Example:
fs.createReadStream('large.mp4').pipe(res)
Output: Readable stream
fs.createWriteStream(path)
Description: Stream tulis file.
Example:
fs.createWriteStream('output.txt').write('data')
Output: Writable stream
fs/promises
Description: Versi Promise dari semua fs method.
Example:
import fs from 'fs/promises'; await fs.readFile('file.txt')
Output: Promise-based

PATH

path.join(...paths)
Description: Gabung path secara aman.
Example:
path.join('/home', 'user', 'file.txt')
Output: /home/user/file.txt
path.resolve(...paths)
Description: Resolve ke absolute path.
Example:
path.resolve('src', 'app.js')
Output: /home/user/project/src/app.js
path.basename(p)
Description: Nama file dari path.
Example:
path.basename('/home/file.txt')
Output: 'file.txt'
path.basename(p, ext)
Description: Nama file tanpa ekstensi.
Example:
path.basename('/home/file.txt', '.txt')
Output: 'file'
path.dirname(p)
Description: Nama folder dari path.
Example:
path.dirname('/home/file.txt')
Output: '/home'
path.extname(p)
Description: Ekstensi file.
Example:
path.extname('index.html')
Output: '.html'
path.parse(p)
Description: Parse path ke object.
Example:
path.parse('/home/file.txt')
Output: { root: '/', dir: '/home', base: 'file.txt', ext: '.txt', name: 'file' }
path.format(obj)
Description: Format object ke path string.
Example:
path.format({ dir: '/home', base: 'file.txt' })
Output: '/home/file.txt'
path.isAbsolute(p)
Description: Cek absolute path.
Example:
path.isAbsolute('/home')
Output: true
path.relative(from, to)
Description: Relative path dari from ke to.
Example:
path.relative('/a/b', '/a/c/file.txt')
Output: '../c/file.txt'
path.normalize(p)
Description: Normalisasi path (buang .. dan .).
Example:
path.normalize('/a//b/../c')
Output: '/a/c'
path.sep
Description: Separator path OS (/ atau \).
Example:
path.sep
Output: '/'
path.delimiter
Description: Delimiter PATH OS (: atau ;).
Example:
path.delimiter
Output: ':'

OS

os.platform()
Description: Platform OS.
Example:
os.platform()
Output: 'linux' | 'darwin' | 'win32'
os.arch()
Description: Arsitektur CPU.
Example:
os.arch()
Output: 'x64' | 'arm64'
os.cpus()
Description: Info CPU cores.
Example:
os.cpus()
Output: [{ model: '...', speed: 3200 }]
os.totalmem()
Description: Total RAM dalam bytes.
Example:
os.totalmem()
Output: 17179869184
os.freemem()
Description: RAM kosong dalam bytes.
Example:
os.freemem()
Output: 8589934592
os.homedir()
Description: Home directory user.
Example:
os.homedir()
Output: '/home/user'
os.tmpdir()
Description: Temp directory.
Example:
os.tmpdir()
Output: '/tmp'
os.hostname()
Description: Hostname komputer.
Example:
os.hostname()
Output: 'my-laptop'
os.networkInterfaces()
Description: Info network interfaces.
Example:
os.networkInterfaces()
Output: { lo: [...], eth0: [...] }
os.uptime()
Description: Uptime sistem dalam detik.
Example:
os.uptime()
Output: 3600
os.EOL
Description: End of line karakter OS.
Example:
os.EOL
Output: '\n' | '\r\n'

HTTP

http.createServer(cb)
Description: Buat HTTP server.
Example:
http.createServer((req, res) => { res.end('Hello') }).listen(3000)
Output: Server di port 3000
res.writeHead(code, headers)
Description: Set status code & header response.
Example:
res.writeHead(200, { 'Content-Type': 'application/json' })
Output: Header terkirim
res.end(data)
Description: Akhiri response (kirim data opsional).
Example:
res.end(JSON.stringify({ ok: true }))
Output: Response selesai
res.write(data)
Description: Kirim chunk data (streaming).
Example:
res.write('chunk1'); res.write('chunk2'); res.end()
Output: Data terkirim
req.url
Description: URL request.
Example:
req.url
Output: '/api/users?id=1'
req.method
Description: HTTP method request.
Example:
req.method
Output: 'GET' | 'POST' | ...
req.headers
Description: Headers request.
Example:
req.headers['content-type']
Output: 'application/json'
req.on('data', cb)
Description: Terima body request (stream).
Example:
req.on('data', chunk => { body += chunk })
Output: Chunk data
req.on('end', cb)
Description: Body request selesai diterima.
Example:
req.on('end', () => { console.log(body) })
Output: Body lengkap
http.get(url, cb)
Description: HTTP GET request sederhana.
Example:
http.get('http://api.example.com', (res) => {})
Output: Response
http.request(options, cb)
Description: Custom HTTP request.
Example:
const req = http.request({ hostname: 'api.example.com', method: 'POST' }, cb); req.write(data); req.end()
Output: Request terkirim

HTTPS

https.createServer(options, cb)
Description: Buat HTTPS server.
Example:
https.createServer({ key, cert }, cb).listen(443)
Output: Server HTTPS
https.get(url, cb)
Description: HTTPS GET request.
Example:
https.get('https://api.example.com', res => {})
Output: Response

EVENTS

new EventEmitter()
Description: Buat event emitter.
Example:
const ee = new EventEmitter()
Output: EventEmitter
.on(event, listener)
Description: Daftarkan listener event.
Example:
ee.on('data', (payload) => {})
Output: Listener terdaftar
.once(event, listener)
Description: Listener sekali jalan.
Example:
ee.once('ready', () => {})
Output: Sekali saja
.emit(event, ...args)
Description: Trigger event.
Example:
ee.emit('data', { id: 1 })
Output: Event triggered
.off(event, listener)
Description: Hapus listener event.
Example:
ee.off('data', handler)
Output: Listener dihapus
.removeAllListeners(event)
Description: Hapus semua listener event.
Example:
ee.removeAllListeners('data')
Output: Semua listener dihapus
.listenerCount(event)
Description: Jumlah listener event.
Example:
ee.listenerCount('data')
Output: 3
.eventNames()
Description: Array nama event yang terdaftar.
Example:
ee.eventNames()
Output: ['data', 'error']
.setMaxListeners(n)
Description: Set maksimum listener (default 10).
Example:
ee.setMaxListeners(20)
Output: Limit 20

STREAM

Readable
Description: Stream yang bisa dibaca.
Example:
new Readable({ read(size) {} })
Output: Readable stream
Writable
Description: Stream yang bisa ditulis.
Example:
new Writable({ write(chunk, enc, cb) {} })
Output: Writable stream
Transform
Description: Stream baca-tulis (modifikasi data).
Example:
new Transform({ transform(chunk, enc, cb) {} })
Output: Transform stream
Duplex
Description: Stream baca & tulis (independen).
Example:
new Duplex({ read() {}, write() {} })
Output: Duplex stream
stream.pipeline(...streams, cb)
Description: Pipe stream dengan error handling otomatis.
Example:
pipeline(readable, transform, writable, (err) => {})
Output: Pipeline selesai
stream.finished(stream, cb)
Description: Callback saat stream selesai/error.
Example:
finished(writable, (err) => { console.log('done') })
Output: Stream selesai
stream.Readable.from(iterable)
Description: Buat readable stream dari iterable.
Example:
Readable.from(['a', 'b', 'c'])
Output: Readable stream

CRYPTO

crypto.randomBytes(size)
Description: Generate random bytes.
Example:
crypto.randomBytes(16).toString('hex')
Output: 'a1b2c3d4...'
crypto.randomUUID()
Description: Generate random UUID v4.
Example:
crypto.randomUUID()
Output: '550e8400-e29b-...'
crypto.createHash(algorithm)
Description: Buat hash (sha256, md5, dll).
Example:
crypto.createHash('sha256').update('data').digest('hex')
Output: Hash hex
crypto.createHmac(algorithm, key)
Description: Buat HMAC.
Example:
crypto.createHmac('sha256', 'secret').update('data').digest('hex')
Output: HMAC hex
crypto.createCipheriv(algo, key, iv)
Description: Enkripsi data.
Example:
crypto.createCipheriv('aes-256-cbc', key, iv)
Output: Cipher
crypto.createDecipheriv(algo, key, iv)
Description: Dekripsi data.
Example:
crypto.createDecipheriv('aes-256-cbc', key, iv)
Output: Decipher
crypto.pbkdf2(password, salt, iter, len, algo, cb)
Description: Hash password dengan salt.
Example:
crypto.pbkdf2('pass', 'salt', 100000, 64, 'sha512', (err, key) => {})
Output: Derived key
crypto.timingSafeEqual(a, b)
Description: Bandingkan buffer aman dari timing attack.
Example:
crypto.timingSafeEqual(buf1, buf2)
Output: true / false

CHILD-PROCESS

child_process.exec(cmd, cb)
Description: Jalankan command shell.
Example:
exec('ls -la', (err, stdout, stderr) => {})
Output: stdout
child_process.execSync(cmd)
Description: Jalankan command synchronous.
Example:
execSync('ls -la')
Output: Buffer stdout
child_process.spawn(cmd, args)
Description: Jalankan proses (stream).
Example:
spawn('ls', ['-la'])
Output: ChildProcess
child_process.fork(module)
Description: Jalankan module Node.js di proses baru.
Example:
fork('./worker.js')
Output: ChildProcess
child_process.execFile(file, args, cb)
Description: Jalankan file tanpa shell.
Example:
execFile('node', ['--version'], cb)
Output: stdout

UTIL

util.promisify(fn)
Description: Ubah callback-based function ke Promise.
Example:
const readFile = util.promisify(fs.readFile)
Output: Async function
util.types.isPromise(val)
Description: Cek apakah value adalah Promise.
Example:
util.types.isPromise(Promise.resolve())
Output: true
util.types.isDate(val)
Description: Cek apakah value adalah Date.
Example:
util.types.isDate(new Date())
Output: true
util.format(format, ...args)
Description: Format string seperti printf.
Example:
util.format('%s %d', 'hello', 42)
Output: 'hello 42'
util.inspect(obj, options)
Description: String representasi objek (debug).
Example:
util.inspect({ a: 1 }, { colors: true, depth: null })
Output: String berwarna
util.deprecate(fn, msg)
Description: Tandai fungsi sebagai deprecated.
Example:
const oldFn = util.deprecate(fn, 'Use newFn instead')
Output: Deprecation warning
util.callbackify(asyncFn)
Description: Ubah async function ke callback-based.
Example:
util.callbackify(asyncFn)((err, result) => {})
Output: Callback

ASSERT

assert.ok(value, msg)
Description: Assert value truthy.
Example:
assert.ok(true, 'harus true')
Output: Tidak error
assert.strictEqual(a, b)
Description: Assert a === b.
Example:
assert.strictEqual(1, 1)
Output: Tidak error
assert.deepStrictEqual(a, b)
Description: Assert deep equal (objek).
Example:
assert.deepStrictEqual({ a: 1 }, { a: 1 })
Output: Tidak error
assert.throws(fn)
Description: Assert function throw error.
Example:
assert.throws(() => { throw new Error('fail') })
Output: Tidak error
assert.rejects(asyncFn)
Description: Assert async function reject.
Example:
await assert.rejects(() => Promise.reject('err'))
Output: Tidak error
assert.fail(msg)
Description: Selalu gagal.
Example:
assert.fail('harus gagal')
Output: AssertionError

NPM-PNPM

npm init
Description: Inisialisasi package.json.
Example:
npm init -y
Output: package.json dibuat
npm install
Description: Install semua dependency dari package.json.
Example:
npm install
Output: node_modules/
npm install <pkg>
Description: Install package (dependencies).
Example:
npm install express
Output: Package terinstall
npm install -D <pkg>
Description: Install sebagai devDependencies.
Example:
npm install -D typescript
Output: Dev dependency
npm install -g <pkg>
Description: Install global.
Example:
npm install -g nodemon
Output: Global
npm uninstall <pkg>
Description: Hapus package.
Example:
npm uninstall express
Output: Package dihapus
npm update
Description: Update semua package.
Example:
npm update
Output: Package diupdate
npm run <script>
Description: Jalankan script dari package.json.
Example:
npm run dev
Output: Script berjalan
npx <command>
Description: Jalankan package tanpa install.
Example:
npx create-next-app@latest
Output: Package berjalan
pnpm install
Description: Install dengan pnpm (lebih cepat).
Example:
pnpm install
Output: node_modules/
pnpm add <pkg>
Description: Install package dengan pnpm.
Example:
pnpm add react
Output: Package terinstall
npm list
Description: Lihat daftar package terinstall.
Example:
npm list --depth=0
Output: Daftar package
npm outdated
Description: Cek package yang outdated.
Example:
npm outdated
Output: Daftar outdated
npm audit
Description: Cek vulnerability.
Example:
npm audit
Output: Laporan security
npm audit fix
Description: Auto-fix vulnerability.
Example:
npm audit fix
Output: Vulnerability diperbaiki

MODULE-SYSTEM

require(module)
Description: Import module (CommonJS).
Example:
const fs = require('fs')
Output: Module
module.exports
Description: Export dari file (CommonJS).
Example:
module.exports = { fn }
Output: Ter-export
exports.name
Description: Export named (CommonJS).
Example:
exports.myFn = fn
Output: Ter-export
import * as name from 'module'
Description: Import semua (ESM).
Example:
import * as fs from 'fs'
Output: Namespace
import { name } from 'module'
Description: Import named (ESM).
Example:
import { readFile } from 'fs'
Output: Named import
import defaultExport from 'module'
Description: Import default (ESM).
Example:
import express from 'express'
Output: Default import
export default
Description: Export default (ESM).
Example:
export default function fn() {}
Output: Default export
export { name }
Description: Export named (ESM).
Example:
export { fn1, fn2 }
Output: Named export
export const name = ...
Description: Export inline (ESM).
Example:
export const PORT = 3000
Output: Inline export
import.meta.url
Description: URL modul saat ini (ESM).
Example:
import.meta.url
Output: 'file:///path/to/file.js'
import.meta.dirname
Description: Dirname modul (ESM, Node 21+).
Example:
import.meta.dirname
Output: '/path/to'

PACKAGE-JSON

"name"
Description: Nama package (lowercase, no space).
Example:
"name": "my-app"
Output: Nama
"version"
Description: Versi semantik (1.0.0).
Example:
"version": "1.0.0"
Output: Versi
"main"
Description: Entry point (CommonJS).
Example:
"main": "index.js"
Output: Entry CJS
"module"
Description: Entry point (ESM).
Example:
"module": "index.mjs"
Output: Entry ESM
"type"
Description: "module" untuk ESM, "commonjs" untuk CJS.
Example:
"type": "module"
Output: ESM
"scripts"
Description: Custom script (npm run ...).
Example:
"scripts": { "dev": "node app.js" }
Output: npm run dev
"dependencies"
Description: Package untuk production.
Example:
"dependencies": { "express": "^4.18.0" }
Output: Production deps
"devDependencies"
Description: Package untuk development.
Example:
"devDependencies": { "typescript": "^5.0.0" }
Output: Dev deps
"peerDependencies"
Description: Dependency yang harus diinstall user.
Example:
"peerDependencies": { "react": "^18.0.0" }
Output: Peer deps
"engines"
Description: Versi Node.js minimal.
Example:
"engines": { "node": ">=18.0.0" }
Output: Node >=18
"exports"
Description: Package exports map (modern).
Example:
"exports": { ".": "./index.js", "./utils": "./utils.js" }
Output: Export map