Computer >> Computer tutorials >  >> Programming >> Javascript

How to read and write a file using Javascript?


You cannot read or write files in JS on client side(browsers). This can be done on serverside using the fs module in Node.js. It provides sync and async functions to read and write files on the file system. Let us look at the exmaples of reading and writing files using the fs module on node.js

Let us create a js file named main.js having the following code −

var fs = require("fs");
console.log("Going to write into existing file");
// Open a new file with name input.txt and write Simply Easy Learning! to it.
fs.writeFile('input.txt', 'Simply Easy Learning!', function(err) {
   if (err) {
      return console.error(err);
   }
   console.log("Data written successfully!");
   console.log("Let's read newly written data");
   // Read the newly written file and print all of its content on the console
   fs.readFile('input.txt', function (err, data) {
      if (err) {
         return console.error(err);
      }
      console.log("Asynchronous read: " + data.toString());
   });
});

Now run the main.js to see the result −

$ node main.js

Output

Going to write into existing file
Data written successfully!
Let's read newly written data
Asynchronous read: Simply Easy Learning!

You can read more about how fs module works in node and how to use it at https://www.tutorialspoint.com/nodejs/nodejs_file_system.htm.