RUNTIME_ENVIRONMENT::ACTIVE

NODE.js

JavaScript unshackled from the browser. Event-driven. Non-blocking. Server-side.

terminal — node
$ node --version
v20.11.0
$ node -e "console.log('Hello, Node.js')"
Hello, Node.js
_

01 // SYNTAX

MODERN_JS_PROTOCOLS

Variable Scope

ES6

Block-scoped declarations. No more hoisting chaos.

let mutable = 'changeable';
const immutable = 'locked';
// const objects can still mutate

Arrow Functions

FAT_ARROW

Lexical this binding. Concise syntax for callbacks.

// Implicit return
const add = (a, b) => a + b;
// Block body
const greet = name => {
return `Hi ${name}`;
}

Destructuring

UNPACK

Extract values into distinct variables.

const { id, name } = user;
const [first, ...rest] = array;
// Nested unpacking
const { data: { items } } = response;

Template Literals

BACKTICK

String interpolation and multi-line support.

const msg = `Hello ${user}
Today: ${new Date()}`
// Tagged templates
sql`SELECT * FROM ${table}`

Spread & Rest

...

Expand arrays or collect parameters.

// Spread
const merged = [...a, ...b];
const clone = { ...original };
// Rest params
const sum = (...nums) => nums.reduce(...)

Promises

ASYNC

Escape callback hell with chainable futures.

fetch(url)
.then(res => res.json())
.then(data => process(data))
.catch(err => handle(err));

02 // ARCHITECTURE

MODULE_SYSTEMS

CommonJS

CJS

The original Node module system. Dynamic, synchronous, runtime-based.

// Import
const fs = require('fs');
const { util } = require('./utils');
// Export
module.exports = { foo, bar };
exports.single = value;
Sync Dynamic Legacy

ES Modules

ESM ⭐

The modern standard. Static analysis, tree-shaking, top-level await.

// Import
import fs from 'fs';
import { helper } from './utils.js';
import * as utils from './utils';
// Export
export default main;
export const helper = () => {};
export { foo, bar };
Static Tree-shake Modern

03 // EVENT_LOOP

CONCURRENCY_MODEL
🔄
Event Loop
Single Thread
Timers
I/O
Idle
Check
Priority Queue:
1. nextTickQueue
2. microTaskQueue
3. timerQueue
event_loop_demo.js
setTimeout(() => console.log('1: Timer'), 0);
setImmediate(() => console.log('2: Immediate'));
process.nextTick(() => console.log('3: nextTick'));
Promise.resolve().then(() => console.log('4: Promise'));
console.log('5: Sync');
// Output Order: 5 → 3 → 4 → 1 → 2
process.nextTick()
Executes after current operation, before event loop continues
setImmediate()
Executes in check phase after I/O callbacks
setTimeout()
Minimum delay, executes in timers phase

04 // ASYNC_PATTERNS

CONTROL_FLOW
SYNCHRONOUS_SYNTAX

Async / Await

async function getUserData(userId) {
try {
const user = await fetchUser(userId);
const orders = await fetchOrders(user.id);
const processed = await process(orders);
return processed;
} catch (err) {
console.error('Failed:', err);
throw new Error('User fetch failed');
}
}
// Top-level await (ES2022)
const data = await fetchData();
✓ Error Handling
Standard try/catch blocks instead of .catch() chains. Stack traces are cleaner.
✓ Debugging
Set breakpoints inside async functions. Step through like synchronous code.
✓ Conditionals
Easy to use if statements and loops with async operations.

05 // DATA_STREAMS

MEMORY_EFFICIENT

Stream Processing

// Pipeline pattern
fs.createReadStream('input.txt')
.pipe(zlib.createGzip())
.pipe(fs.createWriteStream('output.txt.gz'))
.on('finish', () => console.log('Compressed'));
📖
Readable
Source streams
✍️
Writable
Destination streams
🔄
Duplex
Both read & write
Transform
Modify in transit

Buffers

Fixed-size binary data chunks. Essential for TCP streams and file operations.

Buffer.from('hello')
Buffer.alloc(1024)
buf.toString('utf8')
Memory Tip
Streams process data in chunks vs loading entire files into memory.

06 // SYSTEM_OPS

OS_INTERFACE

fs File System

fs.readFile() Async read
fs.writeFile() Async write
fs.mkdir() Create dir
fs.stat() File info
Promise API
Use fs.promises for async/await compatibility

proc Process & ENV

process.argv
// Command line arguments
node script.js --port 3000
process.argv[2] // --port
process.env
const dbUrl = process.env.DATABASE_URL;
const isDev = process.env.NODE_ENV === 'development';
Child Processes
const { exec, spawn } = require('child_process');
exec('ls -la', (err, stdout) => {...});
⚠️ Security
Never commit .env files. Use dotenv package for local dev only.