fs.promises Round Trips Config Files
Save a JSON config file with fs.promises.writeFile and read it back with readFile, keeping one async round trip for the whole config lifecycle.
Code
import { readFile, writeFile } from 'node:fs/promises';
interface CacheConfig {
maxEntries: number;
ttlMs: number;
}
// writeFile serializes the whole config file in one call
async function saveConfig(path: string, config: CacheConfig): Promise<void> {
await writeFile(path, JSON.stringify(config, null, 2), 'utf8');
}
// readFile returns the stored bytes; JSON.parse restores the shape
async function loadConfig(path: string): Promise<CacheConfig> {
const raw = await readFile(path, 'utf8');
return JSON.parse(raw) as CacheConfig;
}
async function main(): Promise<void> {
const configPath = 'cache.config.json';
await saveConfig(configPath, { maxEntries: 128, ttlMs: 60_000 });
const loaded = await loadConfig(configPath);
console.log(`round trip restored: maxEntries=${loaded.maxEntries} ttlMs=${loaded.ttlMs}`);
console.log(`stored bytes: ${(await readFile(configPath, 'utf8')).length}`);
}
main();Output
Captured from a sandboxed run of this snippet in the build pipeline.
round trip restored: maxEntries=128 ttlMs=60000
stored bytes: 41One async round trip, two functions
saveConfig(path, config) serializes the whole CacheConfig in a single call — await writeFile(path, JSON.stringify(config, null, 2), 'utf8') — and loadConfig(path) reads the stored bytes with await readFile(path, 'utf8') and restores the shape with JSON.parse(raw) as CacheConfig. main() drives both against cache.config.json with { maxEntries: 128, ttlMs: 60_000 }.
The round-trip lines
round trip restored: maxEntries=128 ttlMs=60000
stored bytes: 41
The first line proves the parsed object carried the same fields that were written; the second measures the on-disk payload — the pretty-printed JSON of those two fields, 41 characters including newlines and indentation.
The line that restores the shape
return JSON.parse(raw) as CacheConfig;
The as CacheConfig cast is the boundary where the type system trusts the file: JSON.parse returns any, and everything downstream (loaded.maxEntries, loaded.ttlMs) is typed only because of it.
Interactive Tools for This Topic
FAQ
- Do I need to install anything before running this?
- Nothing needs installing: `node:fs/promises` ships with Node.js itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.