01 // SYNTAX
MODERN_JS_PROTOCOLSVariable Scope
ES6Block-scoped declarations. No more hoisting chaos.
let mutable = 'changeable';
const immutable = 'locked';
// const objects can still mutate
Arrow Functions
FAT_ARROWLexical this binding. Concise syntax for callbacks.
// Implicit return
const add = (a, b)
=> a + b;
// Block body
const greet = name
=> {
return `Hi
${name}`;
}
Destructuring
UNPACKExtract values into distinct variables.
const { id, name } = user;
const [first, ...rest] = array;
// Nested unpacking
const { data: { items } } = response;
Template Literals
BACKTICKString 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
ASYNCEscape callback hell with chainable futures.
fetch(url)
.then(res => res.json())
.then(data => process(data))
.catch(err => handle(err));
02 // ARCHITECTURE
MODULE_SYSTEMSCommonJS
CJSThe 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_EFFICIENTStream 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_INTERFACEfs 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
node script.js --port 3000
process.argv[2] // --port
process.env
const dbUrl = process.env.DATABASE_URL;
const isDev = process.env.NODE_ENV === 'development';
const isDev = process.env.NODE_ENV === 'development';
Child Processes
const { exec, spawn } = require('child_process');
exec('ls -la', (err, stdout) => {...});
exec('ls -la', (err, stdout) => {...});
⚠️ Security
Never commit .env files. Use dotenv package for
local dev only.