Node.js Reference
0. Basics
0.1 Hello World
// console.log automatically appends a newline to the output
console.log("Hello, World!");Hello, World!
0.2 Building & Running
Node.js is a runtime for JavaScript. Use the
node command to execute scripts.
# Execute a JavaScript file using Node.js
node main.jsHello, World!
0.3 Comments
// Single-line comment for brief annotations
/* Multi-line
comment block for more extensive notes */(No output)
0.4 Imports
Using CommonJS require (standard for Node.js
CLI tools).
const fs = require('fs'); // File system module
const path = require('path'); // Path utility module
const { parseArgs } = require('util'); // Selective import from utility module(No output)
0.5 Exit Codes
// Terminate the process immediately
// exit(0) for success, non-zero for error (e.g., 1)
process.exit(1); (Process exits with status 1)
0.6 Error Handling
try {
// Manually throw a new Error object
throw new Error("something went wrong");
} catch (e) {
// Catch and print the error message
console.log(e.message);
} finally {
// Always execute this block
console.log("Cleanup");
}something went wrong
Cleanup
1. Environment, Variables & Time
1.1 Variable Declaration
let x = 5; // Block-scoped mutable variable
const Y = 10; // Block-scoped immutable constant
var z = 1; // Function-scoped variable (legacy)(No output)
1.2 Integer Types & Limits
JavaScript numbers are 64-bit floats. BigInt
is used for arbitrary-precision integers.
// Maximum safe integer for standard Number type
console.log(Number.MAX_SAFE_INTEGER);
// BigInt literal defined by 'n' suffix
let large = 9007199254740991n; 9007199254740991
1.3 Casting
let i = Math.floor(3.14); // Explicit truncation to integer
let n = Number("1.23"); // String to numeric conversion
let s = String(100); // Numeric to string conversion
let p = parseInt("10px"); // Parse integer from string (result: 10)(No output)
1.4 Environment Variables
// Access an environment variable via process.env
const path = process.env.PATH;
// Set/Update an environment variable for the current process
process.env.APP_ENV = "production";(No output)
1.5 Time Measurement & Formatting
// High-resolution performance measurement in nanoseconds
const start = process.hrtime.bigint();
const elapsed = process.hrtime.bigint() - start;
// Date and time formatting
const now = new Date();
console.log(now.toISOString()); // ISO 8601 string2024-05-16T12:00:00.000Z (example)
2. Operators & Regex
2.1 Arithmetic & Logic
let a = 10 / 3; // Standard division (3.333)
let b = Math.floor(10 / 3); // Floor division (3)
let c = 10 ** 3; // Exponentiation (1000)
let d = true && false; // Logical AND (false)(No output)
2.2 Regex & Pattern Matching
Native regex literals or RegExp objects.
const re = /\$(\d+)/; // Regex pattern to match '$' followed by digits
const match = re.exec("Price: $100");
if (match) {
console.log(match[1]); // Print first capture group: "100"
}100
3. Argument Parsing
3.1 Argument Parsing
Standard utility since Node.js 18.3.
const { parseArgs } = require('util');
// Configuration for expected CLI flags
const options = {
verbose: { type: 'boolean', short: 'v' },
output: { type: 'string', short: 'o' }
};
// Parse process.argv
const { values, positionals } = parseArgs({ options, strict: false });
// console.log(values.verbose);(No output)
4. Functions & Memory
4.1 Declaration & Returns
// Standard function with default parameter
function add(a, b = 0) { return a + b; }
// Concise arrow function
const multiply = (a, b) => a * b;
// Multi-return via Object destructuring
function getStatus() { return { code: 200, msg: "OK" }; }
const { code, msg } = getStatus();(No output)
4.2 References & Pointers
Objects and Arrays are passed by reference in JavaScript.
function modify(o) {
// Directly modifies the property of the passed object
o.val += 1;
}
let myObj = { val: 10 };
modify(myObj); // myObj.val is now 11(No output)
5. Control Flow
5.1 Conditionals (If/Else)
Standard branching logic. JavaScript uses
if, else if, and
else.
const x = 10;
if (x > 5) {
console.log("Greater");
} else if (x === 5) {
console.log("Equal");
} else {
console.log("Less");
}Greater
5.2 Switch / Case
JavaScript uses the switch statement for
multi-way branching.
const val = 2;
switch (val) {
case 1:
console.log("One");
break;
case 2:
case 3:
console.log("Two or Three");
break;
default:
console.log("Other");
}Two or Three
5.3 Basic Loops (While/For)
Iterative execution using for or
while.
// Standard for loop (0 to 2)
for (let i = 0; i < 3; i++) {
console.log(`for: ${i}`);
}
let x = 0;
while (x < 3) {
console.log(`while: ${x}`);
x++;
}for: 0
for: 1
for: 2
while: 0
while: 1
while: 2
5.4 Breaking & Continue
Controlling loop flow.
for (let x = 0; x < 10; x++) {
if (x < 2) continue; // Skip iteration
if (x === 5) break; // Exit loop
console.log(x);
}2
3
4
5.5 Iterating Collections
Accessing items in arrays or objects using various iteration methods.
// Iterating over Array values
for (const val of [10, 20]) {
console.log(`val: ${val}`);
}
// Iterating over Object entries
const obj = { a: 1, b: 2 };
for (const [key, val] of Object.entries(obj)) {
console.log(`${key}: ${val}`);
}val: 10
val: 20
a: 1
b: 2
6. Strings & Files
6.1 String Manipulation
let s = " Hello ";
s = s.trim().toUpperCase(); // Result: "HELLO"
let sub = s.substring(0, 2); // Result: "HE"
let joined = ["a", "b"].join("-"); // Result: "a-b"(No output)
6.2 Path Joining
const path = require('path');
// Join path segments using OS-specific separators
const p = path.join("/", "usr", "bin");(No output)
6.3 Streaming I/O (Chunks)
const fs = require('fs');
// Create a readable stream with a 4KB buffer
const rs = fs.createReadStream("data.bin", { highWaterMark: 4096 });
rs.on('data', (chunk) => {
// 'chunk' is a Buffer containing the data
});(No output)
6.4 Read to Memory
const fs = require('fs');
// Synchronous read to Buffer (binary)
const buffer = fs.readFileSync("file.bin");
// Synchronous read to UTF-8 String
const text = fs.readFileSync("file.txt", "utf8");(No output)
7. Binary & Bitwise
7.1 Allocation & Packing
Node.js uses the Buffer class for binary
manipulation.
const { Buffer } = require('buffer');
// Allocate a 12-byte buffer
const buf = Buffer.alloc(12);
// Pack a 32-bit Big-Endian integer
buf.writeInt32BE(42, 0);
// Pack a 64-bit Big-Endian double
buf.writeDoubleBE(3.14, 4);(No output)
7.2 Bitwise Operations
let res = 0b1010 & 0b1100; // Bitwise AND
res = 0b1010 | 0b1100; // Bitwise OR
res = 0b1010 ^ 0b1100; // Bitwise XOR
res = ~0b1010; // Bitwise NOT (complement)
res = 0b0001 << 2; // Bitwise Shift Left (0b0100)(No output)
7.3 Hex Conversion
// Convert integer to hex string
let s = (255).toString(16); // "ff"
// Parse hex string to integer
let val = parseInt("ff", 16); // 255(No output)
8. Collections & JSON
8.1 Lists, Maps & Sets
let l = [1, 2]; l.push(3); // Array (Dynamic List)
let m = new Map(); m.set("k", 1); // Key-Value Map
let s = new Set([1, 1, 2]); // Unique values Set ({1, 2})(No output)
8.2 JSON Parsing
// Parse JSON string into JavaScript object
const data = JSON.parse('{"id": 42}');
// Serialize JavaScript object to JSON string
const s = JSON.stringify(data);(No output)
9. Systems & Networking
9.1 TCP Server & Client
const net = require('net');
// Simple TCP Echo Server
const srv = net.createServer((c) => {
c.on('data', (d) => c.write(d));
});
srv.listen(8080);
// TCP Client connection
const cli = net.createConnection({ port: 80 }, "example.com", () => {
cli.write("GET / HTTP/1.0\r\n\r\n");
});(No output)
9.2 UDP Server & Client
const dgram = require('dgram');
// Create a UDP IPv4 socket
const s = dgram.createSocket('udp4');
// Send datagram payload to address:port
s.send("ping", 8080, "127.0.0.1");(No output)
9.3 Concurrency
JavaScript handles concurrency via an event loop and Promises.
async function main() {
// Pause execution until the promise resolves
const result = await Promise.resolve("Done");
console.log(result);
}
main();Done
9.4 SQLite
const { execSync } = require('child_process');
// Execute sqlite3 CLI command synchronously
const out = execSync('sqlite3 :memory: "SELECT 42;"');
console.log(out.toString().trim());42