Node.js Reading and Writing Files
Use the promise-based filesystem API for a clear asynchronous workflow. Specify encoding when a file is intended to contain text rather than arbitrary bytes.
How it works
The example creates a fresh temporary directory, writes one fictional report with exclusive creation and reads it back as UTF-8. A finally block removes only the directory returned by mkdtemp. This avoids overwriting a learner’s existing report and keeps the cleanup target tied to an owned resource. It does not teach deletion of a user-selected folder or make a durability claim about storage hardware.
Run the code
Run this example locally with Node.js. The exact sources are reviewed on Node 22.15.1 and Node 24.22.1 unless a specialised lab states otherwise. Save the complete source as owned-files.mjs in a separate empty exercises folder and run node owned-files.mjs. There is no Node.js browser runner on Bhylu; the plain JavaScript playground does not provide these filesystem, server or process APIs.
Download the complete source. Ordinary Node scripts need no Apache, PHP or MySQL service. File examples own their temporary folders; network fixtures use loopback and available temporary ports.
Example
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const folder = await mkdtemp(join(tmpdir(), 'bhylu-node-'));
import { writeFile, readFile } from 'node:fs/promises';
try {
const file = join(folder, 'inventory.txt');
await writeFile(file, 'tripod:3\nbinoculars:2\n', { encoding: 'utf8', flag: 'wx' });
const text = await readFile(file, 'utf8');
console.log(text.trim().split('\n').length);
console.log(text.startsWith('tripod:3'));
} finally {
await rm(folder, { recursive: true, force: true });
}
Expected result
2 true
The two rows are decoded intentionally and checked without printing a machine-specific directory. Reading a whole file is convenient for small bounded inputs; a large untrusted source needs a size and streaming strategy.
Use the Node.js API reference for the precise version contract.