File System (fs)
import { readFile, writeFile, readdir, stat, mkdir } from 'fs/promises';
// Read file
const data = await readFile('file.txt', 'utf8');
// Write file
await writeFile('out.txt', 'hello');
// List directory
const files = await readdir('.', { withFileTypes: true });
// Check if exists
const info = await stat('file.txt').catch(() => null);
// Create directory
await mkdir('new-dir', { recursive: true });
Path Module
import path from 'path';
path.join('/users', 'docs', 'file.txt') // /users/docs/file.txt
path.resolve('./src') // /absolute/path/src
path.extname('file.txt') // .txt
path.basename('/a/b/file.txt') // file.txt
path.dirname('/a/b/file.txt') // /a/b
HTTP Server
import http from 'http';
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ hello: 'world' }));
});
server.listen(3000);
Process & Environment
process.env.NODE_ENV // Environment variable
process.cwd() // Current working directory
process.argv // CLI arguments
process.exit(1) // Exit with code
process.on('uncaughtException', console.error);
Child Process
import { exec, execSync, spawn } from 'child_process';
// Quick command
const output = execSync('ls -la', { encoding: 'utf8' });
// Streaming output
const child = spawn('npm', ['test']);
child.stdout.on('data', chunk => process.stdout.write(chunk));