The reading room
Node.js guides.
File processing, command-line scripts, streams, and server fundamentals using built-in Node.js modules.
35 guides · Examples, explanations, and practical limits.
In this topic
35 articles
Read a UTF-8 text file in Node.js
Read a small text file with the promise-based readFile API and an explicit UTF-8 encoding. The resolved result is a string rather than a Buffer when an encoding is…
Write a small JSON file in Node.js
Serialize a value with JSON.stringify and write it using UTF-8. Add a final newline for a file that is easy to inspect with text tools, and read it back when checking…
Append a line to a text file
Use appendFile to add text at the end of a file, creating the file if needed. Include the line separator explicitly; the API does not insert one for you.
Create nested directories in Node.js
Use mkdir with recursive true when a script needs a directory tree that might not exist yet. Await creation before writing a file inside the final directory.
List directory entries and their types
Pass withFileTypes to readdir when you need entry names and basic type checks. The returned Dirent objects can distinguish ordinary files and directories without…
Inspect a file’s size and type
Use stat to inspect metadata such as byte size and whether a path refers to a regular file. A text file’s size is measured in bytes, not JavaScript characters.
Handle a missing file by its error code
Attempt the read and handle ENOENT when a missing file has an expected fallback. Avoid a separate existence check, because the path can change between checking and…
Create a file only when it does not already exist
Use writeFile with the wx flag to create a new file and fail if that path already exists. This expresses the exclusivity requirement in the file operation itself.
Copy a file with explicit destination behavior
Use copyFile to duplicate a regular file. Add COPYFILE_EXCL when overwriting an existing destination would be a mistake rather than the intended behavior.
Rename a file within a directory
Use rename to move a path within a filesystem. For a simple rename, build both paths explicitly and await the operation before using the destination.
Create an isolated temporary directory
Use mkdtemp with a prefix inside the operating system’s temporary directory. Keep the returned path and remove that exact directory after the operation has finished.
Read a file incrementally with readline
Combine createReadStream with readline to process a text file one line at a time. This avoids collecting the complete file into one string before processing begins.
Copy a stream with pipeline error handling
Use the promise-based pipeline helper to connect readable and writable streams. Await it so completion and stream errors reach normal async control flow.
Compress a file with a gzip stream
Insert createGzip between a readable file stream and a writable stream to compress incrementally. A pipeline coordinates backpressure and provides an awaitable…
Calculate a file’s SHA-256 digest incrementally
Feed a file stream into a SHA-256 hash when you need a content fingerprint without reading the complete file into a Buffer. Digest the hash only after all chunks have…
Join filesystem path segments portably
Use node:path join for filesystem path segments instead of manually inserting slash characters. It applies the platform’s path rules and normalizes ordinary separators.
Resolve a file relative to an ES module
Resolve a resource with new URL and import.meta.url when it belongs beside an ES module. This avoids depending on the directory from which the user launched Node.js.
Parse command-line options with util.parseArgs
Use util.parseArgs for a small command-line interface with named options. Declare option types and decide explicitly whether unexpected flags or positional arguments…
Validate numeric environment variables
Environment variables arrive as strings or undefined. Validate a complete value and its allowed range before using it as a port, timeout, or worker count.
Report CLI failure with process.exitCode
Set process.exitCode when a command should report failure after finishing normal cleanup. This lets the event loop and pending output complete instead of forcing…
Run a child command without a shell
Use execFile with an argument array when you need a child executable without shell interpolation. Keep the executable and arguments separate instead of building a…
Read child-process output as a stream
Use spawn when child output should be consumed incrementally. Attach an error listener for launch failures and observe close for the final status after standard…
Measure UTF-8 text in bytes with Buffer
Use Buffer.byteLength when a Node.js limit is expressed in encoded bytes. JavaScript string length counts UTF-16 code units and is not a reliable UTF-8 byte count.
Encode and decode Base64 with Buffer
Use Buffer to convert bytes to Base64 and back. When the original content is text, specify its encoding explicitly at both ends of the round trip.
Await a delay with timers/promises
Use the promise-based setTimeout API for an awaitable delay in Node.js. Import it under a clear name so it is not confused with the callback-based global function.
Await one EventEmitter event
Use events.once to await a single EventEmitter event. Register the wait before triggering the event so a synchronous emission cannot happen before the listener exists.
Create a readable stream from an iterable
Use Readable.from to expose an iterable as a Node.js readable stream. It is useful when a downstream API expects a stream but your producer naturally yields records.
Serve JSON from a minimal Node HTTP server
Use node:http to create a small HTTP server, set the response content type, and end the response with serialized JSON. Every request path should receive an explicit…
Check HTTP status before reading fetch JSON
Fetch does not reject just because an HTTP response has a 404 or 500 status. Check response.ok before interpreting the body as successful application data.
Give an operation a timeout signal
Use AbortSignal.timeout to create a signal that aborts after a deadline. Pass it to APIs that support cancellation rather than merely racing their promise against a…
Consume a Web ReadableStream in Node.js
A Web ReadableStream can provide chunks through async iteration in Node.js. Decode byte chunks with a streaming decoder when character sequences can cross chunk…
Move a small CPU task into a worker thread
Use a worker thread for CPU-bound JavaScript that would otherwise occupy the main event loop. A worker can receive input and return a result through messages.
Measure a code interval with performance.now
Use performance.now for elapsed-time measurements inside one process. It supplies a monotonic high-resolution time reference rather than a wall-clock timestamp…
Read Node.js process memory measurements
Use process.memoryUsage to inspect several different memory measurements. Heap usage, resident memory, and external allocations describe different parts of the…
Cancel a pending file read with AbortController
ReadFile accepts an AbortSignal so a caller can stop waiting for an unneeded read. Handle cancellation distinctly from ordinary filesystem errors when your workflow…
No matching articles. Try another title or topic.