Skip to content

Reading and Writing Files (fs module)

Programming Node.js Difficulty 1/5

Beginning of the lesson

Reading and Writing Files (the fs module)

Save and load text on disk with Node.js

Big Idea: Node.js can open real files on your computer, read what is inside, and write new content back. The built-in fs ("file system") module gives you the tools. This is how programs remember things after they stop running.
By the end you will be able to:
  • load the fs module with require,
  • read a file as text and write text back,
  • tell the difference between synchronous, callback, and promise styles,
  • choose the right style for the job.

1. Meet the fs module

The fs module is built into Node — you do not install anything. You just require it at the top of your file:

const fs = require('fs');

Now the variable fs holds many helpful functions, such as readFileSync, readFile, writeFileSync, and appendFileSync. Notice that some names end in Sync and some do not — that difference is the heart of this lesson.

2. Reading a file (synchronous)

The simplest way to read is fs.readFileSync. The word Sync means "synchronous": Node stops and waits until the whole file is read, then hands you the result.

const fs = require('fs');

// Read the whole file, THEN continue
const text = fs.readFileSync('poem.txt', 'utf8');
console.log(text);

// Output:
// Roses are red,
// Node reads files fast.

Always pass 'utf8' as the second argument. Without it, Node gives you a Buffer (raw bytes shown as numbers) instead of a readable string. With 'utf8', you get normal text you can print.

Because it waits, the next line only runs after the file is fully read. Simple to think about — but Node can do nothing else while it waits.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers