Node.js ยท Chapter 8 of 43

Reading & Writing Files (fs)

The `fs` (File System) module lets Node.js interact with files: reading, writing, appending, and deleting them, both synchronously and asynchronously.

Asynchronous methods are preferred in real applications because they don't block the rest of the program while waiting for disk I/O.

Reading files

`fs.readFile()` reads a file asynchronously with a callback; `fs.readFileSync()` blocks until done and returns the data directly.

Writing files

`fs.writeFile()` writes data to a file, creating it if it doesn't exist, or overwriting it if it does.

Example 1 (javascript)
const fs = require('fs');
fs.readFile('data.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});
Output
Hello file contents

readFile is asynchronous; the callback runs once the file is loaded.

Example 2 (javascript)
fs.writeFile('out.txt', 'Saved!', (err) => {
  if (err) throw err;
  console.log('File written');
});
Output
File written

writeFile creates or overwrites out.txt with the given content.

Key points

  • fs module handles file reading and writing.
  • Async methods (readFile/writeFile) don't block execution.
  • Sync methods (readFileSync/writeFileSync) block until finished.
  • Always encode as 'utf8' to get readable text instead of a Buffer.
๐Ÿ’ก Note: Prefer async fs methods on servers to avoid blocking other requests.

๐Ÿ“ Quick Quiz

1. Which method reads a file asynchronously?

2. What does fs.writeFile() do if the file doesn't exist?

3. Why prefer async fs methods on a server?