File System Operations in Node.js
Introduction to File System Module
The Node.js File System (fs) module provides an API for interacting with the file system. It supports both synchronous and asynchronous operations.
Basic File Operations
Reading Files
const fs = require('fs');
// Asynchronous file reading
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
console.log('File content:', data);
});
// Synchronous file reading
try {
const data = fs.readFileSync('example.txt', 'utf8');
console.log('File content:', data);
} catch (err) {
console.error('Error reading file:', err);
}
Writing Files
// Asynchronous writing
fs.writeFile('output.txt', 'Hello, World!', 'utf8', (err) => {
if (err) console.error('Error writing file:', err);
else console.log('File written successfully');
});
// Appending to file
fs.appendFile('output.txt', '\nAppended text', 'utf8', (err) => {
if (err) console.error('Error appending:', err);
});
Working with Streams
// Reading large files with streams
const readableStream = fs.createReadStream('large-file.txt');
readableStream.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data`);
});
// Writing with streams
const writableStream = fs.createWriteStream('output.txt');
writableStream.write('First chunk\n');
writableStream.end('Final chunk');
Directory Operations
// Creating directory
fs.mkdir('new-directory', { recursive: true }, (err) => {
if (err) console.error('Error creating directory:', err);
});
// Reading directory contents
fs.readdir('.', (err, files) => {
if (err) console.error('Error reading directory:', err);
else console.log('Directory contents:', files);
});
Best Practices
- Use asynchronous operations for better performance
- Handle errors properly
- Use streams for large files
- Check file existence before operations
Conclusion
The Node.js File System module provides comprehensive tools for working with files and directories. Understanding these operations is essential for building robust applications.