Node.js: Code Outside the Browser / Built in Modules

File System (fs module)

πŸ“¦ The fs Module

fs (File System) is a built-in Node.js module for reading, writing, and managing files and folders. Every method below comes in two flavors β€” sync and async β€” depending on whether you want your code to wait or keep moving.


πŸ“ Synchronous (Blocking)

Sync methods pause your code until the file operation finishes. Nothing else runs until the write or read completes β€” simple to reason about, but risky in apps that need to stay responsive.

const fs = require('fs');

// Write
fs.writeFileSync('note.txt', 'This is a sync write.');
console.log('βœ… File written successfully!');

// Read
const data = fs.readFileSync('note.txt', 'utf8');
console.log('πŸ“„ File content:', data);
  • writeFileSync(path, content) creates the file if it doesn't exist, or overwrites it if it does.

  • readFileSync(path, 'utf8') returns the file's content as a plain string. Skip 'utf8' and you'd get raw binary data instead.

  • Because these are sync, console.log only runs after the operation finishes β€” no waiting or callback needed.

⏳ Asynchronous (Non-blocking)

Async methods use a callback (or promises) so your app doesn't freeze while the disk does its work. This matters most in servers, where blocking would stall every other request.

const fs = require('fs');
// Write
fs.writeFile('async.txt', 'This is an async write.', (err) => {
  if (err) throw err;
  console.log('βœ… Async file written!');
});
// Read
fs.readFile('async.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log('πŸ“„ Async file content:', data);
});
  • writeFile and readFile return immediately β€” the rest of your script keeps running while the file operation happens in the background.

  • The callback (err, data) fires once the operation finishes. err holds an error if something went wrong; check it before using data.

  • Since these don't block, the order things print to the console can differ from the order you wrote the code in.


βž• Appending to Files

Adds content to the end of a file without wiping out what's already there β€” unlike writeFileSync, which overwrites everything.

fs.appendFileSync('note.txt', '\nThis is appended.');
console.log('πŸ“ Content appended!');

File after append:

This is a sync write.
This is appended.
  • The \n adds a line break first, so the new text starts on its own line instead of running into the existing content.

  • If the file doesn't exist yet, appendFileSync creates it β€” same as writeFileSync.


πŸ—‘οΈ Deleting Files

fs.unlinkSync('note.txt');
console.log('πŸ—‘οΈ File deleted!');

⚠️ unlinkSync removes the file permanently β€” there's no trash or undo. If the file doesn't exist, this throws an error and crashes your script unless you handle it.

βœ… Delete Safely

const fs = require('fs');
const filePath = 'note.txt';

if (fs.existsSync(filePath)) {
  fs.unlinkSync(filePath);
  console.log('πŸ—‘οΈ File deleted!');
} else {
  console.log('❌ File not found.');
}
  • existsSync(path) checks whether the file is there first, and returns true or false.

  • Wrapping the delete in that check means your code handles a missing file gracefully instead of throwing an error.


πŸ“ Working with Folders

Starting point β€” just the project file itself, no myFolder yet:

project/
└── app.js

Step 1 β€” Create a folder:

fs.mkdirSync('myFolder');
console.log('πŸ“ Folder created!');

mkdirSync makes a new, empty folder at the given path. It throws an error if a folder with that name already exists.

project/
β”œβ”€β”€ app.js
└── myFolder/        ← new, empty

Step 2 β€” Create a file inside it:

fs.writeFileSync('myFolder/info.txt', 'Hello from inside the folder!');

Same writeFileSync as before β€” just pointed at a path inside the folder you just made.

project/
β”œβ”€β”€ app.js
└── myFolder/
    └── info.txt      ← new

Step 3 β€” Clean up: delete the file, then the folder:

fs.unlinkSync('myFolder/info.txt'); // delete file first
fs.rmdirSync('myFolder');           // then delete the folder
console.log('🧹 Folder cleaned up!');
  • Folders must be empty before rmdirSync can remove them β€” that's why the file inside gets deleted first.

  • Trying to delete the folder while it still has files in it will throw an error.

project/
└── app.js            ← back to the starting point