🎓 A1Learner
🔍
0 of 50 lessons completed

Writing Files

The fs module also writes files to the disk. Writing makes a new file or replaces an old one.

Writing a file

This writes Hello, Node! to greeting.txt.

const fs = require("fs");

fs.writeFileSync("greeting.txt", "Hello, Node!");

Adding to a file

This adds words to the file from the last snippet. The print shows the full text.

fs.appendFileSync("greeting.txt", " Welcome back!");
console.log(fs.readFileSync("greeting.txt", "utf8"));

Writing without waiting

This writes a short note without waiting. The callback prints Written when the write ends.

fs.writeFile("note.txt", "A short note", (error) => {
  if (error) return;
  console.log("Written");
});

Example

const fs = require("fs");

fs.writeFileSync("greeting.txt", "Hello, Node!");
console.log("File written");
console.log(fs.readFileSync("greeting.txt", "utf8"));

Key points

  • writeFileSync writes text to a file.
  • writeFileSync makes the file when it does not exist.
  • writeFileSync replaces the whole file when it exists.
  • appendFileSync adds new text after the old text.
  • appendFileSync keeps the old text in place.
  • writeFile writes a file without waiting.

In this example, writeFileSync writes Hello, Node! to greeting.txt. The first print shows File written. The program then reads the file back. The last print shows the text that was written.

Note

Writing without a wait uses a callback, like reading.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does writeFileSync do to a file that already exists?