fs module in Node JS
The fs
(File System) module in Node.js provides an API to interact with the file system, allowing you to perform operations like reading, writing, and manipulating files and directories. It is a core module, meaning it comes bundled with Node.js and does not require separate installation.
Key Features of the fs
Module
- File Operations: Read from and write to files.
- Directory Operations: Create, remove, and list directories.
- File System Metadata: Retrieve information about files and directories (e.g., size, creation time).
1. Synchronous vs. Asynchronous Methods
The fs
module provides both synchronous and asynchronous methods for file operations. Asynchronous methods are preferred in Node.js to avoid blocking the event loop.
Asynchronous Methods
- Non-blocking: These methods use callbacks or promises to handle operations and allow the program to continue executing other code while waiting for the file system operation to complete.
Synchronous Methods
- Blocking: These methods block the execution of subsequent code until the file operation is complete. They are simpler to use but can cause performance issues in a high-concurrency environment.
2. Commonly Used Methods
a. Reading Files
Asynchronous:
fs.readFile()
const fs = require('fs'); fs.readFile('example.txt', 'utf8', (err, data) => { if (err) { console.error('Error reading file:', err); return; } console.log('File contents:', data); });
Synchronous:
fs.readFileSync()
const fs = require('fs'); try { const data = fs.readFileSync('example.txt', 'utf8'); console.log('File contents:', data); } catch (err) { console.error('Error reading file:', err); }
b. Writing Files
Asynchronous:
fs.writeFile()
const fs = require('fs'); fs.writeFile('example.txt', 'Hello, World!', 'utf8', (err) => { if (err) { console.error('Error writing file:', err); return; } console.log('File written successfully'); });
Synchronous:
fs.writeFileSync()
const fs = require('fs'); try { fs.writeFileSync('example.txt', 'Hello, World!', 'utf8'); console.log('File written successfully'); } catch (err) { console.error('Error writing file:', err); }
c. Appending to Files
Asynchronous:
fs.appendFile()
const fs = require('fs'); fs.appendFile('example.txt', 'Appended text.', 'utf8', (err) => { if (err) { console.error('Error appending to file:', err); return; } console.log('Text appended successfully'); });
Synchronous:
fs.appendFileSync()
const fs = require('fs'); try { fs.appendFileSync('example.txt', 'Appended text.', 'utf8'); console.log('Text appended successfully'); } catch (err) { console.error('Error appending to file:', err); }
d. Deleting Files
Asynchronous:
fs.unlink()
const fs = require('fs'); fs.unlink('example.txt', (err) => { if (err) { console.error('Error deleting file:', err); return; } console.log('File deleted successfully'); });
Synchronous:
fs.unlinkSync()
const fs = require('fs'); try { fs.unlinkSync('example.txt'); console.log('File deleted successfully'); } catch (err) { console.error('Error deleting file:', err); }
e. Reading Directory Contents
Asynchronous:
fs.readdir()
const fs = require('fs'); fs.readdir('.', (err, files) => { if (err) { console.error('Error reading directory:', err); return; } console.log('Directory contents:', files); });
Synchronous:
fs.readdirSync()
const fs = require('fs'); try { const files = fs.readdirSync('.'); console.log('Directory contents:', files); } catch (err) { console.error('Error reading directory:', err); }
f. Creating and Removing Directories
Creating Directory:
Asynchronous:
fs.mkdir()
const fs = require('fs'); fs.mkdir('newDir', (err) => { if (err) { console.error('Error creating directory:', err); return; } console.log('Directory created successfully'); });
Synchronous:
fs.mkdirSync()
const fs = require('fs'); try { fs.mkdirSync('newDir'); console.log('Directory created successfully'); } catch (err) { console.error('Error creating directory:', err); }
Removing Directory:
Asynchronous:
fs.rmdir()
const fs = require('fs'); fs.rmdir('newDir', (err) => { if (err) { console.error('Error removing directory:', err); return; } console.log('Directory removed successfully'); });
Synchronous:
fs.rmdirSync()
const fs = require('fs'); try { fs.rmdirSync('newDir'); console.log('Directory removed successfully'); } catch (err) { console.error('Error removing directory:', err); }
3. Streams
The fs
module also supports streams for efficient file operations, especially for large files.
- Readable Streams: For reading data from a file.
- Writable Streams: For writing data to a file.
Example: Reading a File Stream
const fs = require('fs');
const readableStream = fs.createReadStream('example.txt', 'utf8');
readableStream.on('data', (chunk) => {
console.log('Received chunk:', chunk);
});
readableStream.on('end', () => {
console.log('Stream ended');
});
Example: Writing to a File Stream
const fs = require('fs');
const writableStream = fs.createWriteStream('example.txt', 'utf8');
writableStream.write('Hello, World!\n');
writableStream.write('Appending more text.\n');
writableStream.end();
4. Error Handling
When working with the fs
module, always handle errors to ensure your application can manage unexpected issues gracefully. For example, handle errors in callbacks or use try-catch blocks for synchronous methods.
Summary
- Synchronous vs. Asynchronous: Use asynchronous methods to avoid blocking the event loop in Node.js.
- Common Methods: Includes
readFile
,writeFile
,appendFile
,unlink
,readdir
,mkdir
,rmdir
, and more. - Streams: Efficiently handle large files with readable and writable streams.
- Error Handling: Ensure proper error handling to manage file system operations effectively.