• Tutorials Logic, IN
  • +91 8092939553
  • info@tutorialslogic.com

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

										    
											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