← Back to Node.js Course | Chapter 5: File System | Lesson 7 of 7

fs.promises

fs.promises gives you the same file functions but returning promises, ready for async/await.

In this page:

  1. fs.promises
Syntax
javascript
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

javascript
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/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting await
  2. Mixing callbacks and promises
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.