fs.promises
fs.promises gives you the same file functions but returning promises, ready for async/await.
In this page:
Syntax
const fs = require('fs/promises');
const data = await fs.readFile('path', 'utf8');
await fs.writeFile('path', data);
fs.promises
Import from fs/promises or fs.promises. Each function returns a promise, so use await inside async functions. It combines well with Promise.all for reading many files in parallel and keeps servers non-blocking.
Note:
require("fs/promises") is a shorter way to import the promise API.
Example: fs.promises
const fs = require("fs/promises");
(async () => {
await fs.writeFile("a.txt", "AAA");
await fs.writeFile("b.txt", "BB");
const [a, b] = await Promise.all([fs.readFile("a.txt", "utf8"), fs.readFile("b.txt", "utf8")]);
console.log(a, b, (await fs.stat("a.txt")).size);
})();
// Output:
// AAA BB 3
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Forgetting await
- Mixing callbacks and promises
- Reading files sequentially when parallel is possible
Chapter Summary
- fs/promises returns promises
- Use with async/await
- Promise.all reads in parallel
- Non-blocking
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: