File System Basics
Imagine you have a diary where you write notes, read them later, and sometimes tear out pages. In Node.js, the **File System (fs) module** lets you do exactly that with files on your computer – create, read, update, and delete files.
What is the File System Module?
The fs module provides an API for interacting with the file system in a way modeled on standard POSIX functions. It lets you work with files and directories – reading, writing, deleting, renaming, and more.
Think of the fs module as your personal file manager – but instead of clicking and dragging, you write code to do it.
Two Ways to Use fs Module
The fs module provides both synchronous and asynchronous methods:
- Synchronous: Blocking – waits for operation to complete. Method names end with `Sync`.
- Asynchronous: Non-blocking – takes a callback. This is the preferred way in Node.js.
Importing the fs Module
const fs = require('fs');Reading Files (Asynchronous)
<!-- Create a file called sample.txt with some content -->
fs.readFile('sample.txt', 'utf8', (err, data) => { if (err) { console.error('Error reading file:', err); return; } console.log('File content:', data);});
console.log('Reading file... (this prints first!)');Reading Files (Synchronous)
try { const data = fs.readFileSync('sample.txt', 'utf8'); console.log('File content:', data);} catch (err) { console.error('Error reading file:', err);}console.log('This prints after reading (synchronous)');Writing Files
<!-- Asynchronous write -->const content = 'Hello, this is a new file!nCreated with Node.js';
fs.writeFile('newfile.txt', content, 'utf8', (err) => { if (err) { console.error('Error writing file:', err); return; } console.log('File written successfully!');});
<!-- Synchronous write -->try { fs.writeFileSync('sync-file.txt', 'Synchronous write'); console.log('Sync file written');} catch (err) { console.error(err);}Appending to Files
Add content to the end of an existing file.
fs.appendFile('newfile.txt', 'nThis line is appended.', (err) => { if (err) throw err; console.log('Content appended!');});Checking if a File Exists
<!-- Modern way (since Node.js v10) -->const fsPromises = require('fs').promises;
async function checkFile() { try { await fsPromises.access('sample.txt'); console.log('File exists'); } catch { console.log('File does not exist'); }}
checkFile();Deleting Files
fs.unlink('file-to-delete.txt', (err) => { if (err) { console.error('Error deleting file:', err); return; } console.log('File deleted successfully');});Error Handling is Important!
Always handle errors when working with files – files might not exist, permissions might be wrong, disks might be full.
<!-- Asynchronous with proper error handling -->fs.readFile('nonexistent.txt', 'utf8', (err, data) => { if (err) { if (err.code === 'ENOENT') { console.log('File not found!'); } else { console.error('Other error:', err); } return; } console.log(data);});Working with File Descriptors (Advanced)
For more control, you can open files and work with file descriptors:
fs.open('data.txt', 'r', (err, fd) => { if (err) throw err; <!-- Read from the file using the file descriptor --> const buffer = Buffer.alloc(100); fs.read(fd, buffer, 0, buffer.length, 0, (err, bytesRead, buffer) => { console.log(buffer.toString('utf8', 0, bytesRead)); <!-- Always close the file descriptor --> fs.close(fd, (err) => { if (err) throw err; }); });});Two Minute Drill
- fs module lets you work with files – read, write, append, delete.
- Use asynchronous methods (callbacks) for non-blocking operations.
- Synchronous methods (with `Sync`) are simpler but block the event loop.
- Always handle errors – files may not exist or permissions may be wrong.
- For modern code, consider using `fs.promises` with async/await.
Need more clarification?
Drop us an email at career@quipoinfotech.com
