The fs Promises API
Use fs/promises with async/await for cleaner file code.
Syntax
const fs = require('fs/promises');
await fs.readFile(path, 'utf8');The fs/promises API returns promises instead of using callbacks, so it pairs naturally with async/await. This is the modern, recommended way to work with files.
Benefits
- No callback nesting.
- Errors handled with
try...catch. - Reads top to bottom like ordinary code.
Example
const fs = require('fs/promises');
async function run() {
try {
await fs.writeFile('log.txt', 'Line 1\n');
await fs.appendFile('log.txt', 'Line 2\n');
const text = await fs.readFile('log.txt', 'utf8');
console.log(text);
} catch (err) {
console.error('File error:', err.message);
}
}
run();When to use it
- A data pipeline awaits each `fs/promises.readFile` call sequentially so files are processed in order without deeply nested callbacks.
- An image-processing service uses `Promise.all` with `fs/promises.readFile` to read multiple images in parallel before batch-resizing them.
- A build tool uses `fs/promises.writeFile` inside an async function to serialize compiled output and `await` each write before moving to the next step.
More examples
Async/await file read
Uses `fs/promises.readFile` with `async/await` for clean, readable asynchronous file reading.
const fs = require('fs/promises');
async function readConfig() {
const raw = await fs.readFile('config.json', 'utf8');
return JSON.parse(raw);
}
readConfig().then(cfg => console.log(cfg));Write then read with promises
Chains a write and a read with `await` -- sequential and easy to follow compared to nested callbacks.
const { writeFile, readFile } = require('fs/promises');
async function main() {
await writeFile('data.txt', 'Node promises!', 'utf8');
const content = await readFile('data.txt', 'utf8');
console.log(content); // 'Node promises!'
}
main();Parallel reads with Promise.all
Reads multiple files in parallel using `Promise.all` -- much faster than awaiting each one in sequence.
const { readFile } = require('fs/promises');
async function loadAll(files) {
const contents = await Promise.all(
files.map(f => readFile(f, 'utf8'))
);
return contents;
}
loadAll(['a.txt', 'b.txt', 'c.txt'])
.then(all => console.log(all));
Discussion