Node.js File System
Node.js File System Module (fs)
The fs module in Node.js facilitates interactions with the file system, allowing reading, writing, updating, deleting, and managing files and directories. It operates synchronously and asynchronously, giving developers flexibility based on the application’s needs.
Importing the fs Module
To utilize the file system module, it must first be imported using require:
const fs = require('fs');
This allows access to numerous built-in functions designed for handling files.
File Operations
Below the types of file operations :
1. Reading a File
The fs.readFile() method is employed to retrieve file contents asynchronously.
Syntax
fs.readFile(path, encoding, callback);
- path : The location of the file.
- encoding : The character encoding (e.g., utf8).
- callback : A function executed after reading, receiving an error and data parameter.
Example
fs.readFile('example.txt', 'utf8', (err, data) => { if (err) { console.error('Error reading file:', err); return; } console.log('File content:', data); });
2. Writing to a File
To store data inside a file, fs.writeFile() is used asynchronously.
Syntax
fs.writeFile(path, data, encoding, callback);
- path : File location.
- data : Content to write.
- encoding : Optional encoding format.
- callback : Function executed upon completion.
Example
fs.writeFile('output.txt', 'Hello, Node.js!', 'utf8', (err) => { if (err) { console.error('Write operation failed:', err); return; } console.log('File saved successfully!'); });
3. Appending Data
fs.appendFile() allows appending new content to an existing file without overwriting.
Syntax
fs.appendFile(path, data, encoding, callback);
Example
fs.appendFile('log.txt', '\nNew entry added!', 'utf8', (err) => { if (err) throw err; console.log('Data appended!'); });
4. Deleting a File
To remove a file permanently, fs.unlink() is utilized.
Syntax
fs.unlink(path, callback);
Example
fs.unlink('obsolete.txt', (err) => { if (err) { console.error('File deletion error:', err); return; } console.log('File deleted successfully!'); });
5. Creating a Directory
The fs.mkdir() method is used to establish a new directory.
Syntax
fs.mkdir(path, options, callback);
Example
fs.mkdir('new_folder', { recursive: true }, (err) => { if (err) throw err; console.log('Directory created!'); });
6. Removing a Directory
For directory deletion, fs.rmdir() is effective.
Syntax
fs.rmdir(path, callback);
Example
fs.rmdir('old_folder', (err) => { if (err) throw err; console.log('Directory removed!'); });
Conclusion
The Node.js fs module provides comprehensive methods for handling files and directories. It supports both synchronous and asynchronous operations, empowering developers to manage file-based tasks efficiently while maintaining optimal performance.