fs.promises
- Node.js course
- Beginner
- Lesson 100/116
- 5 min
Learn async file operations with fs.promises.
What is fs.promises?
In Node.js, file operations use the fs module. For asynchronous work the fs.promises sub-object is preferred; its methods return Promises and work with await.
import fs from 'fs/promises';
const data = await fs.readFile('notes.txt', 'utf8');Here fs/promises provides Promise-based methods directly. The old fs module is callback-based; modern code prefers fs/promises. readFile, writeFile and appendFile are the most common methods.
import and await
You import the fs/promises module with import. In an ES modules environment you can use await directly at the top level of the module; otherwise you wrap it in an async function.
import fs from 'fs/promises';
async function run() {
const data = await fs.readFile('notes.txt', 'utf8');
console.log(data);
}
run();Here the run async function awaits readFile and logs the content. The 'utf8' argument makes the result come back as a string; without it you get a Buffer.
Practice Your turn: write with fs.promises
Import the module with import fs from 'fs/promises'. Define an async function run(). Inside, write to a file with await fs.writeFile('hello.txt', 'hello'). Log a message with console.log('written'). Call run().
Starter code
// Import the fs/promises module
// Define async function run
// Write with await fs.writeFile, log with console.log
// Call runSample solution
import fs from 'fs/promises';
async function run() {
await fs.writeFile('hello.txt', 'hello');
console.log('written');
}
run();Expected output
written
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why is fs/promises preferred over the old fs module?
- Because it returns Promises and works with await Correct answer
- Because it uses less memory
- Because it runs faster
- Because it is required
Explanation: The Promise-based API enables a flat flow with await.
2 Fill in the blank: import fs
____ fs from 'fs/promises';
import fs from 'fs/promises';
Explanation: import brings in fs/promises.
3 fs/promises parts
| Term | Meaning |
|---|---|
import |
imports the module |
fs/promises |
Promise-based fs |
await |
waits for result |