Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

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.
  • Writing a File.
  • Opening a File.
  • Deleting a File.

Reading a File

Reading a File Asynchronously

example
let fs = require('fs');

fs.readFile('file.txt', function (error, data) {
	if (error) throw error;
	    console.log(data);
});

Reading a File Synchronously

example
let fs = require('fs');

let data = fs.readFileSync('file.txt', 'utf8');
console.log(data);

Writing a File

Writing a File Asynchronously

example
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

example
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.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.