NodeJS File System
File System
File system module in NodeJS allow us to work with the file system on our computer, and it can be easily included using require() method. The file system module is responsible for all the asynchronous or synchronous file I/O operations. We can perform below common I/O operation using file system module-
Reading a File
Reading a File Asynchronously
let fs = require('fs');
fs.readFile('file.txt', function (error, data) {
if (error) throw error;
console.log(data);
});
Reading a File Synchronously
let fs = require('fs');
let data = fs.readFileSync('file.txt', 'utf8');
console.log(data);
Writing a File
Writing a File Asynchronously
let fs = require('fs');
let content = "NodeJS can write to file.";
fs.writeFile('file.txt', content , (error) => {
if (err) {
throw err;
} else {
console.log('Your Content has been written to file successfully!');
}
});
Writing a File Synchronously
let fs = require('fs');
let content = "NodeJS can write to file.";
fs.writeFileSync('my_file.txt', content);
console.log("Your Content has been written to file successfully!");
Opening a File
Opening a File Asynchronously
Deleting a File
Deleting a File Asynchronously
Key Takeaways
- The fs module provides both synchronous (Sync) and asynchronous methods - prefer async for production.
- Use fs.promises (or fs/promises) for Promise-based file operations with async/await.
- Always handle errors in file operations - files may not exist or permissions may be denied.
- fs.readFile() reads the entire file into memory; use fs.createReadStream() for large files.
- fs.writeFile() overwrites the file; fs.appendFile() adds to the end.
- Use path.join(__dirname, 'filename') to construct reliable file paths.
See Also
Related Node.js Topics