← Learning Hub
Beginner

Reading and Writing Files

The node:fs/promises module reads and writes files. Its functions return promises, so use await. In an .mjs file you can use await at the top level.

Reading and writing files is one of the most common jobs for back-end scripts: config files, logs, uploads, reports, small JSON databases. The promise-based fs API keeps your program responsive while the disk works.

Example
You can edit this code.

JSON files

Many small apps keep data in a JSON file. Read the text, then JSON.parse it:

Example
You can edit this code.

Handling a missing file

Example
You can edit this code.

Folders

Example
You can edit this code.
"utf8" tells Node to give you text. Leave it out and you get a Buffer (raw bytes), which is right for images and PDFs.
Key points
  • Use node:fs/promises with await.
  • JSON.parse and JSON.stringify for JSON files.
  • Handle missing files (ENOENT) gracefully.

📝 Test yourself

1. Which module has promise-based file functions?
2. What error code means 'file not found'?
3. Fill in the function that turns JSON text into an object:
const data = JSON.(text);