π‘ In ESM, get __dirname: import { fileURLToPath } from 'url'; const __dirname = path.dirname(fileURLToPath(import.meta.url));
Module System Globals (CJS only)
Essential npm Commands
package.json Key Fields
Version Ranges in package.json
β οΈ Always commit package-lock.json. Use npm ci in CI/CD.
Useful npx & Global Tools
fs/promises β Modern Way β
Sync & Callback Variants
β οΈ Avoid Sync methods in servers β they block all requests!
File Watching
Check File Exists
path module π₯
os module
URL module (ESM-style)
Raw HTTP Server
fetch (Node 18+) β
HTTPS & Crypto
4 Stream Types
pipe() β Stream Data π₯
Buffer
Custom Readable Stream
process object π₯
stdin / stdout / stderr
dotenv β .env files
Signal Handling & Cleanup
Core API
Custom EventEmitter Class β
events utility
exec & execFile β Simple Commands
spawn β Streaming I/O
fork β Node Subprocesses
Callbacks β Promises β Async/Await
Promise Combinators β
Concurrency Control
Timeout Pattern
Custom Error Classes β
Error Codes Reference
try/catch Best Practices
util module
timers/promises Node 15+
assert module
perf_hooks β Performance
Common Traps
process.nextTick vs setImmediate β nextTick runs before I/O (even before promises!), setImmediate runs after I/O. Use nextTick carefully β stacking it can starve I/O.
require() caches modules β Calling require('./mod') twice returns the same object. Mutating exports affects all importers. To reload: delete from require.cache.
Sync fs methods block everything β Never use readFileSync/writeFileSync in a server request handler. Use promises.
Event listener memory leaks β Default max is 10 listeners. Forgetting to call .off() causes memory leaks. Use emitter.once() for one-time handlers.
JSON.stringify loses undefined β undefined values in objects are dropped: JSON.stringify({a:undefined}) === '{}'. Also: no circular reference support natively.
Promise chain vs async/await errors β In an express route, if you use async and forget try/catch, an unhandled rejection won't be caught by Express error middleware without a wrapper.