Node.jsLesson 8 of 13

The File System Module

The fs module, short for file system, gives Node.js the ability to work with files. You can read them, write them, rename them, and delete them. Browsers block file access on purpose for security, so this is something only a server environment can do. It is one of the main reasons Node.js exists.

The fs module, short for file system, gives Node.js the ability to work with files. You can read them, write them, rename them, and delete them. Browsers block file access on purpose for security, so this is something only a server environment can do. It is one of the main reasons Node.js exists.

The file system module ships with Node.js, so there is nothing to install. The methods you will meet first use callbacks. readFile takes a path, an encoding, and a callback. The callback runs when the read finishes, and it receives an error first, then the data. Checking the error before using the data is a pattern you will see across Node.js.

Slow file work is the perfect place to talk about blocking versus non-blocking code. Node.js can read files two ways: the async methods you use here, and the sync versions with names like readFileSync. Async means the program moves on while the file loads in the background. Sync means the program stops and waits. On a server, sync calls are dangerous, because one slow file read can freeze the whole app for every visitor.

Real projects use the fs module everywhere: saving uploads, reading config files, generating reports, and logging errors to disk. A logger that appends one line per request is a classic first project. This lesson sticks to reading and writing so you can see both directions clearly.

Read a file

Create a file called message.txt with any text inside, then run the script below. readFile reads the whole file and hands it to the callback. If the file does not exist, the error object is filled in and data stays undefined. Always check the error before you use the data, or the program may crash on a missing file.

JS
const fs = require("fs");

fs.readFile("message.txt", "utf8", (err, data) => {
  if (err) {
    console.log("Something went wrong:", err.message);
    return;
  }
  console.log(data);
});

Write a file

writeFile creates the file if it is missing and replaces it if it exists. The second argument is the content you want to save. The callback receives only an error, since there is no data to return. Run the script, then open hello.txt and you should see the new text.

JS
const fs = require("fs");

fs.writeFile("hello.txt", "Hello from Node.js!", (err) => {
  if (err) {
    console.log("Write failed:", err.message);
    return;
  }
  console.log("File saved.");
});

Sync calls: the blocking trap

readFileSync works, and beginners reach for it because it is simpler. But a sync call blocks the event loop: while the disk works, the program answers no one. That is fine in a one-off script, and harmful inside a web server, where every visitor shares that single thread. Use readFile and writeFile, or their promise versions, in any code that serves requests.

JS
// Blocks the whole program until the read finishes
const data = fs.readFileSync("message.txt", "utf8");
console.log(data);

Syntax

JS
const fs = require("fs"); // built-in file system module

fs.readFile("message.txt", "utf8", (err, data) => {
  if (err) {
    console.log("Something went wrong:", err.message); // file missing?
    return; // stop here, do not use data
  }
  console.log(data); // the whole file as one string
});

fs.readFile Callback Has (err, data) Order

Node callbacks are error-first: (err, data) => {}. Swapping order gives silent bugs.

JS
fs.readFile("file.txt", (err,data)=>{ if(err) throw err })

Good to know

  • The fs module is built into Node.js.
  • readFile loads a file, writeFile saves one.
  • Always check the error argument first.
  • Avoid readFileSync inside a web server.
Try it Yourself Edit the code, press Run, then check what changed in the Result.
Ready
Code
Result

Practice makes it stick

Open the Playground and build your own page with the tags you just learned.

→ Open Playground