Node.js File System Module: Read, Write & Manipulate Files
The Node.js File System (fs) module provides a powerful API for interacting with the file system. Whether you need to read, write, delete, or manipulate files, the fs module has you covered. In this guide, we’ll explore the most important methods with practical examples.
To use the module, require it at the top of your file:
const fs = require('fs');
Reading Files
Asynchronous File Reading
fs.readFile reads a file’s contents without blocking the event loop:
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
console.log('File contents:', data);
});
Synchronous File Reading
fs.readFileSync returns the file contents directly and throws on error. Use this only when blocking is acceptable (e.g., startup scripts):
try {
const data = fs.readFileSync('example.txt', 'utf8');
console.log('File contents:', data);
} catch (err) {
console.error('Error reading file:', err);
}
Writing Files
Asynchronous File Writing
fs.writeFile writes data to a file, creating it if it doesn’t exist and overwriting it if it does:
const data = 'Hello, world!';
fs.writeFile('example.txt', data, 'utf8', (err) => {
if (err) {
console.error('Error writing file:', err);
return;
}
console.log('File written successfully');
});
Synchronous File Writing
const data = 'Hello, world!';
try {
fs.writeFileSync('example.txt', data, 'utf8');
console.log('File written successfully');
} catch (err) {
console.error('Error writing file:', err);
}
Manipulating Files and Directories
Renaming Files
fs.rename('oldname.txt', 'newname.txt', (err) => {
if (err) {
console.error('Error renaming file:', err);
return;
}
console.log('File renamed successfully');
});
Deleting Files
fs.unlink('example.txt', (err) => {
if (err) {
console.error('Error deleting file:', err);
return;
}
console.log('File deleted successfully');
});
Creating Directories
fs.mkdir('newdir', (err) => {
if (err) {
console.error('Error creating directory:', err);
return;
}
console.log('Directory created successfully');
});
Async/Await with fs.promises
For cleaner code, use the promise-based API:
const fs = require('fs/promises');
async function readAndLog() {
try {
const data = await fs.readFile('example.txt', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
}
FAQs
Q: Can I read and write binary files with the fs module?
A: Yes. Omit the encoding option or pass 'binary' to work with raw Buffer data.
Q: How do I check if a file exists before reading it?
A: Use fs.existsSync('path/to/file') for a synchronous check.
Q: What is the difference between fs.unlink and fs.rm?
A: fs.unlink only removes files. fs.rm is more versatile — it can also remove directories (with the recursive option).
Q: How do I handle large files efficiently?
A: Use streams. fs.createReadStream and fs.createWriteStream process data in chunks, keeping memory usage low.
Key Takeaways
- Use async methods (
readFile,writeFile) for non-blocking I/O in web servers and APIs. - Use sync methods (
readFileSync,writeFileSync) only in scripts or startup code where blocking is acceptable. - Prefer
fs/promiseswithasync/awaitfor cleaner modern Node.js code. - Use streams for large files to avoid loading everything into memory at once.