Core Node.js APIs
Work with essential built-in APIs including file systems, paths, operating-system information, URLs, events, and environment configuration.
File System Operations
The node:fs and node:fs/promises modules provide APIs for reading, writing, updating, deleting, and inspecting files and directories. Prefer asynchronous APIs in server applications when the operation may involve significant I/O.
Synchronous file operations block the JavaScript execution thread and should generally be reserved for startup tasks or scripts where blocking is acceptable.
import { readFile } from 'node:fs/promises';
const data = await readFile('config.json', 'utf8');
console.log(data);- Prefer asynchronous file APIs in request-handling code.
- Use
node:fs/promisesfor Promise-based file operations. - Avoid blocking file operations inside high-throughput request handlers.
Why should synchronous file operations usually be avoided inside HTTP handlers?
Path, URL, and OS APIs
The path module provides platform-aware path manipulation. The URL API handles URL parsing and construction. The os module provides information about the operating system and hardware.
Use path.join() or path.resolve() rather than manually concatenating file paths so applications work correctly across operating systems.
import path from 'node:path';
const filePath = path.join(process.cwd(), 'data', 'users.json');
const url = new URL('/users?id=10', '[https://example.com');
console.log(filePath);
console.log(url.searchParams.get('id')](https://example.com'%29;
console.log%28filePath%29;
console.log%28url.searchParams.get%28'id'%29));- Use
pathinstead of manual path-string concatenation. - The URL API provides structured access to URL components.
- Platform-aware APIs make applications more portable.
Which API is best suited for joining filesystem paths?
EventEmitter
Node.js uses events extensively. The EventEmitter class allows objects to emit named events and allows listeners to subscribe to them.
Event-driven design can decouple producers from consumers, but excessive event usage can make application flow difficult to understand. Use events when they represent meaningful domain or infrastructure events.
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.on('user.created', (user) => {
console.log('Created:', user.name);
});
emitter.emit('user.created', { name: 'Suriya' });- EventEmitter provides publish-subscribe behavior inside a process.
- Listeners should be removed when their lifecycle requires it.
- Use events carefully to avoid hidden control flow.
Which method emits an EventEmitter event?