File System Module

File System Module (fs)

The File System (fs) module is one of the most heavily used core modules. It gives you direct access to interact with the file system on your computer or server.

Whether you want to read the contents of a text file, create a new log file, delete an old image, or rename a directory, the fs module provides all the tools you need.


1. Synchronous vs. Asynchronous

The fs module provides both asynchronous (non-blocking) and synchronous (blocking) methods. In backend development, you should almost always use the asynchronous methods so that reading a large file doesn't freeze your entire application.

const fs = require('fs');

2. Reading Files

To read a file asynchronously, use the fs.readFile() method.

Read File Example

const fs = require('fs');

const demoFile = 'message.txt';

// Create a small demo file, then read it back asynchronously. fs.writeFile(demoFile, 'Hello from the Node.js file system module!', (writeErr) => { if (writeErr) { console.error('Could not create the demo file:', writeErr.message); return; }

fs.readFile(demoFile, 'utf8', (err, data) => { if (err) { console.error('An error occurred:', err.message); return; } console.log('File contents:', data); }); });

Always specify 'utf8' as the encoding format, otherwise it will return a raw Buffer stream instead of a readable string.


3. Writing and Appending Files

To write data to a file (which will overwrite any existing content), use fs.writeFile(). If you simply want to add text to the end of a file without overwriting it, use fs.appendFile().

Write and Append Example

const fs = require('fs');

// Writing a file fs.writeFile('newfile.txt', 'Hello World!', (err) => { if (err) throw err; console.log('File successfully created and written!'); });

// Appending to a file fs.appendFile('log.txt', '\nUser logged in at 10:00 AM', (err) => { if (err) throw err; console.log('Log entry added!'); });


Exercise

?

Why should you prefer asynchronous `fs` methods over synchronous ones?