Node.js Built-ins Cheatsheet
nodeCore Node.js modules reference — fs, path, http, crypto, events.
fs/promises - File System
fs.readFile(path[, options]): Promise<Buffer | string>Asynchronously reads the entire contents of a file
const data = await fs.readFile('./file.txt', 'utf8');fs.writeFile(path, data[, options]): Promise<void>Asynchronously writes data to a file, replacing the file if it exists
await fs.writeFile('./output.txt', 'Hello World', 'utf8');fs.appendFile(path, data[, options]): Promise<void>Asynchronously appends data to a file, creating the file if it does not exist
await fs.appendFile('./log.txt', 'New log entry\n');fs.readdir(path[, options]): Promise<string[] | Dirent[]>Reads the contents of a directory and returns an array of filenames
const files = await fs.readdir('./src', { withFileTypes: true });fs.mkdir(path[, options]): Promise<string | undefined>Asynchronously creates a directory
await fs.mkdir('./nested/dir', { recursive: true });fs.rm(path[, options]): Promise<void>Removes files and directories, similar to rm -rf
await fs.rm('./temp', { recursive: true, force: true });fs.stat(path[, options]): Promise<Stats>Returns information about a file or directory
const stats = await fs.stat('./file.txt');
console.log(stats.isDirectory(), stats.size);fs.rename(oldPath, newPath): Promise<void>Renames or moves a file or directory
await fs.rename('./old.txt', './new.txt');fs.copyFile(src, dest[, mode]): Promise<void>Asynchronously copies a file from src to dest
await fs.copyFile('./source.txt', './backup.txt');path - Path Utilities
path.join(...paths): stringJoins path segments using the platform-specific separator
path.join('/users', 'john', 'docs'); // '/users/john/docs'path.resolve(...paths): stringResolves a sequence of paths into an absolute path
path.resolve('src', 'index.js'); // '/home/user/project/src/index.js'path.dirname(path): stringReturns the directory name of a path
path.dirname('/users/john/file.txt'); // '/users/john'path.basename(path[, suffix]): stringReturns the last portion of a path, optionally removing a suffix
path.basename('/users/file.txt', '.txt'); // 'file'path.extname(path): stringReturns the extension of a path including the dot
path.extname('index.html'); // '.html'path.parse(path): { root, dir, base, ext, name }Returns an object with path components
path.parse('/home/user/file.txt');
// { root: '/', dir: '/home/user', base: 'file.txt', ext: '.txt', name: 'file' }path.format(pathObject): stringReturns a path string from an object (opposite of parse)
path.format({ dir: '/home/user', name: 'file', ext: '.txt' });
// '/home/user/file.txt'path.relative(from, to): stringReturns the relative path from one path to another
path.relative('/data/users', '/data/files'); // '../files'url - URL Handling
new URL(input[, base]): URLCreates a new URL object by parsing the input relative to base
const url = new URL('/api/users', 'https://example.com');
// https://example.com/api/usersurl.href, url.origin, url.protocol, url.host, url.pathname, url.search, url.hashAccess and modify individual URL components
const url = new URL('https://site.com:8080/path?q=1#hash');
console.log(url.hostname, url.port, url.pathname);url.searchParams.get(name): string | nullReturns the first value of the specified search parameter
const url = new URL('https://site.com?id=123');
url.searchParams.get('id'); // '123'url.searchParams.getAll(name): string[]Returns all values for a search parameter as an array
const url = new URL('?tag=js&tag=node');
url.searchParams.getAll('tag'); // ['js', 'node']url.searchParams.set(name, value): voidSets the value of a search parameter, replacing existing values
url.searchParams.set('page', '2');url.searchParams.append(name, value): voidAppends a new name-value pair to the query string
url.searchParams.append('filter', 'active');url.searchParams.delete(name): voidRemoves all values for the specified parameter
url.searchParams.delete('temp');url.searchParams.has(name): booleanReturns true if the parameter exists
url.searchParams.has('id'); // trueurl.searchParams.entries() | keys() | values() | forEach()Iterate over all search parameters
for (const [key, val] of url.searchParams) {
console.log(key, val);
}crypto - Cryptography
crypto.randomBytes(size): BufferGenerates cryptographically strong random bytes
const token = crypto.randomBytes(32).toString('hex');crypto.randomUUID(): stringGenerates a random RFC 4122 version 4 UUID
const id = crypto.randomUUID();
// 'f47ac10b-58cc-4372-a567-0e02b2c3d479'crypto.createHash(algorithm): HashCreates a Hash object for generating hash digests
const hash = crypto.createHash('sha256')
.update('password')
.digest('hex');crypto.createHmac(algorithm, key): HmacCreates an HMAC object for generating keyed hash digests
const hmac = crypto.createHmac('sha256', 'secret-key')
.update('message')
.digest('hex');crypto.timingSafeEqual(a, b): booleanCompares two buffers in constant time to prevent timing attacks
const a = Buffer.from(userToken);
const b = Buffer.from(storedToken);
const isValid = crypto.timingSafeEqual(a, b);hash.update(data[, encoding]): HashUpdates the hash content with the given data
hash.update('part1').update('part2');hash.digest([encoding]): Buffer | stringCalculates the digest of all data passed to the hash
const result = hash.digest('base64');events - EventEmitter
new EventEmitter(): EventEmitterCreates a new EventEmitter instance
import { EventEmitter } from 'events';
const emitter = new EventEmitter();emitter.on(eventName, listener): thisAdds a listener function for the specified event
emitter.on('data', (payload) => {
console.log('Received:', payload);
});emitter.once(eventName, listener): thisAdds a one-time listener that is removed after first invocation
emitter.once('connect', () => {
console.log('Connected!');
});emitter.emit(eventName[, ...args]): booleanSynchronously calls each listener registered for the event
emitter.emit('data', { id: 1, name: 'test' });emitter.off(eventName, listener): thisRemoves the specified listener from the event
emitter.off('data', myHandler);emitter.removeAllListeners([eventName]): thisRemoves all listeners for the specified event or all events
emitter.removeAllListeners('data');emitter.listenerCount(eventName): numberReturns the number of listeners for the specified event
const count = emitter.listenerCount('data');emitter.eventNames(): (string | symbol)[]Returns an array of event names with registered listeners
const events = emitter.eventNames(); // ['data', 'error']os - Operating System
os.platform(): stringReturns the operating system platform
os.platform(); // 'darwin', 'linux', 'win32'os.arch(): stringReturns the CPU architecture
os.arch(); // 'x64', 'arm64'os.homedir(): stringReturns the path to the current user's home directory
os.homedir(); // '/Users/john' or 'C:\\Users\\john'os.tmpdir(): stringReturns the operating system's default temp directory
os.tmpdir(); // '/tmp' or 'C:\\Users\\john\\AppData\\Local\\Temp'os.cpus(): os.CpuInfo[]Returns an array of objects with info about each logical CPU core
const numCores = os.cpus().length;
const model = os.cpus()[0].model;os.freemem(): numberReturns the amount of free system memory in bytes
const freeGB = (os.freemem() / 1024 ** 3).toFixed(2);os.totalmem(): numberReturns the total amount of system memory in bytes
const totalGB = (os.totalmem() / 1024 ** 3).toFixed(2);os.hostname(): stringReturns the hostname of the operating system
os.hostname(); // 'my-macbook.local'os.type(): stringReturns the operating system name
os.type(); // 'Darwin', 'Linux', 'Windows_NT'