File System Module: Read Files (readFile()), Create Files (appendFile(), open(), writeFile()), Update Files (appendFile(), writeFile()), Delete Files (unlink()), Rename Files (rename())

The fs module gives the server a memory: readFile with an err-first callback, appendFile adds (and creates), writeFile replaces, unlink deletes, rename renames: registrations finally survive a restart.

12 min read · 9 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

The server with amnesia

FestConnect's server takes registrations beautifully: and forgets every one of them at the first restart. They lived in a variable, and variables die with the process.

Mehta-shop economics apply here too: data that matters goes on disk. Node's built-in fs (File System) module is the pen: your server will write each registration to a file, read the list back, and archive it at day's end. Five operations, one module, and the subject's last lesson.

At a glance

The fs verbs (learn the add-vs-replace row twice)

JobMethodBehaviour
Readfs.readFile(path, 'utf8', cb)Delivers the content to your callback
CreateappendFile / open(path, 'w') / writeFileAll 3 create the file if it is missing
Update: addfs.appendFile(path, text, cb)ADDS text at the end
Update: replacefs.writeFile(path, text, cb)REPLACES the entire content
Deletefs.unlink(path, cb)Removes the file
Rename / movefs.rename(oldPath, newPath, cb)Renames; a new folder in the path moves it

Practical

The registration book, full cycle

const fs = require('fs');

// CREATE + UPDATE(add): appendFile creates the file if missing
fs.appendFile('registrations.txt', 'Riya: Garba Night\n', function (err) {
    if (err) throw err;              // err-first: check before trusting
    console.log('Registration saved');
});

// READ: asynchronous, content arrives in the callback
fs.readFile('registrations.txt', 'utf8', function (err, data) {
    if (err) throw err;
    console.log('So far:\n' + data);
});

// UPDATE(replace): writeFile wipes and rewrites
// fs.writeFile('winner.txt', 'Team Pixel', function (err) { ... });

// DELETE and RENAME:
// fs.unlink('old-draft.txt', function (err) { ... });
// fs.rename('registrations.txt', 'day1-archive.txt', function (err) { ... });

This example runs in Gri-Learn on the web, where you can edit it and see the output.

Theory

The err-first callback: Node's handshake

Every fs callback receives err as its first argument: null when all went well, an Error object when it did not (file missing, disk full, no permission).

function (err, data) { if (err) throw err; ... }

This err-first convention is Node-wide law: check err before touching data, every time: an unchecked err means data is undefined and the next line becomes the crash site. It is Unit 3 of BCA403's exception discipline reborn in callback clothing: errors are values here, handed to you, and ignoring a handed error is the one unforgivable style crime in Node.

Quiz

registrations.txt contains 40 entries. The committee runs fs.writeFile('registrations.txt', 'Riya: Garba Night', cb) intending to add one more. What is in the file afterwards?

  1. 41 entries: the new one at the end
  2. Only Riya's single entry: writeFile REPLACED the entire content
  3. 41 entries: the new one at the top
  4. An error: writeFile refuses to touch existing files
Show the answer

Only Riya's single entry: writeFile REPLACED the entire content

writeFile is the whiteboard eraser: whatever the file held is gone, replaced by exactly the new text: 40 registrations destroyed by one wrong verb. ADDING was appendFile's job, and this add-vs-replace pair is both the exam's favourite fs question and a genuinely dangerous real-world slip (there is no undo on a file). Option D imagines a safety interlock that does not exist: writeFile happily overwrites. The habit: before typing a write verb, ask am I adding or replacing?, and let the answer pick the method.

Think first

Predict the print order

In the listing, appendFile is called BEFORE readFile. Is 'Registration saved' guaranteed to print before 'So far:'? Recall which model runs all of fs, then commit to an answer and tap.

Show the answer

Not guaranteed. Both calls are asynchronous: each starts its disk work and returns immediately; the callbacks fire whenever their I/O completes, in whichever order the disk delivers: the code's top-to-bottom order promises nothing about the callbacks' order. (It also means readFile might run before the append lands: possibly missing the newest entry.) Work that DEPENDS on a write belongs INSIDE the write's callback: read after append completes by nesting the readFile there. Third telling of the async model: effects, AJAX, now fs: one model, whole subject.

Watch out

File-handling slips

writeFile when you meant appendFile: the 40-registrations wipe: add vs replace, always consciously chosen.

Skipping the err check: a missing file then crashes you one line later on undefined data, far from the real cause.

Sequencing by line order: async callbacks ignore your file's top-to-bottom poetry: dependencies nest inside callbacks.

Paths are relative to where node ran: the same app.js started from another folder reads and writes THERE.

Theory

FestConnect Live, complete

Walk the whole subject once: data learned to describe itself (XML), the page learned to move (jQuery), the data slimmed down (JSON), the browser learned to fetch without reloading (AJAX), and the server learned to exist, answer queries and now REMEMBER (Node + fs). One coherent app, one language end to end. BCA503-01 takes this stack further next year; the async model and the err-first handshake go with you everywhere JavaScript does.

Summary

Key takeaways

  • require('fs') opens the File System module; every operation is asynchronous with an err-first callback.
  • Read: readFile(path, 'utf8', cb(err, data)); check err before touching data.
  • Create: appendFile, open(path, 'w') and writeFile all create missing files.
  • Update: appendFile ADDS at the end; writeFile REPLACES everything: choose consciously.
  • Delete with unlink; rename (and move) with rename(oldPath, newPath).
  • Callback order follows I/O completion, not code order: dependent work nests inside callbacks.
  • Memory hook: append adds, write wipes, err speaks first.

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Node.js

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

File System Module: Read Files (readFile()), Create Files (appendFile(), open(), writeFile()), Update Files (appendFile(), writeFile()), Delete Files (unlink()), Rename Files (rename()) · Web Designing-2 (option A) · Gri-Learn