DEV Community

Cover image for How to read and write files in JavaScript
Rahul Banerjee
Rahul Banerjee

Posted on • Originally published at realjavascriptproject.com

How to read and write files in JavaScript

Article was originally posted on realjavascriptproject.com

Reading from a file is the process whereby we feed input to a computer program with different types of data contained on the file while writing to a file is the process of outputting contents of a computer program to a file.

The data being operated on by these programs can be of varying types and formats such as text, JSON, XML, and others.

When developing applications we occasionally come across requirements that require us to write or read data from files. For example, you might have a set of numeric values that you want to do a computation on them, and entering these values manually might lead to duplicates and errors in the input.

The most effective and efficient way to solve this problem is to create a program that reads the sets of values from a file, executes the computation, and outputs the results to another file.

In this tutorial, we will learn the different ways that we can leverage to read and write data into a file using JavaScript.

A Common bad practice while using client-side JavaScript

It is considered a bad practice to access the file system of your computer while using client-side JavaScript and very few browsers support this functionality.

This functionality is prevented due to security issues. If any website could have the capability to access the file system of a user's machine, it could lead to a lot of data theft, hacking, and privacy issues.

Internet Explorer might be dead, however you might find the below useful

Internet explorer has an API named ActiveXObject that we can use to get a FileSystemObject to read and write on files. We are going to see this functionality in action in the next section.

There are other alternatives that we can use to realize this functionality such as: using FileReader to read from files and using server-side libraries with runtime environments such as node.

Writing to files in internet explorer using an ActiveXObject.

The ActiveXObject API is only available in internet explorer and is executed using the internet explorer console.

To open the internet explorer console, right-click on the browser and select the option labeled view source, alternatively you can press the F12 button on your computer keyboard.

Select the option labeled Console on the window that opens to open the editor where we will write our code.

Copy and paste the following code into the console.

In the above code, we have created the writeToFile() method that accepts two parameters path and data. The path represents the location where our file will be created and the data represents the contents to be written in the file.

The ActiveXObject() method returns an object that allows us to access the file system by passing the argument Scripting.FileSystemObject.

Call the CreateTextFile() method from the returned object and pass our path to this method and a second boolean parameter containing the value of true.

The true value indicates that the existing file can be overwritten and you should change it to false if otherwise.

The CreateTextFile() method returns a TextStream that allows us to write to the file. Call the Write() method on the returned TextStrem object and pass our data to this method to write it to the file.

Finally, call your custom function writeToFile() and pass the concrete details regarding the path and the data.

To execute the code, press the run button located on the bottom right section of the console window as shown in the following image.

The following image verifies that a file named theFile.txt was created under local disk C and a text containing the value This text was written using a TextStream written into it.

Reading from files in internet explorer using a ActiveXObject.

This example has the same steps as the previous one with the exception that it has its methods to read from a file.

Copy and paste the following code into the internet explorer console.

In the above code, we have created a method named readFromFile() that accepts three parameters, pathdata, and ForReading.

The ForReading method is used to indicate that the file mode will only allow the file to be read. Other modes can be passed such as ForWriting and ForAppending. These modes are represented with the values 12, and 8 respectively.

The code starts with creating and writing a file as we did in the previous example and the next step reads from the created file.

Call the OpenTextFile() from the object returned by ActiveXObject() and pass the path and the ForReading parameters in the method.

The OpenTextFile() method returns a TextStream that allows us to read from the file. Call ReadLine() from from the TextStream object to read from the file. The ReadLine() method will return the contents of the file as a string.

To verify that our file was read, log the contents of the string to the console as shown in the following image.

Press the run button to execute the code and note that the text that we wrote to the file is the same as the one we have logged to the console.

Reading from files using FileReader API

The FileReader API is another we can utilize to read from files but note that it does not read files from the file system but reads files selected using the HTML input tag.

Go to visual studio code and create a file named index.html. copy and paste the following code.

In the above code, we have created an HTML file that contains an input of type file and one paragraph.

Inside the head section, we have added the JavaScript code with will handle the functionality of reading the file that we select.

To retrieve the selected file, we use the querySelector() method and pass the type of input as a parameter to this method.

The readAsText() method reads the contents of the file and returns the result as a string. To display this string to the browser we use the querySelector() and pass class as the parameter to this method to retrieve the paragraph and assign it the result.

Having gained access to the paragraph, we set its innerText value to the result returned by the readAsText() method once the file has been loaded as indicated by the addEventListener() method.

Create a file named file-reader.txt and add the text Reading using a FileWriter inside the file. Open the index.html file in any browser and press the choose file button to select the file-reader.txt file.

The contents we added in the file-reader.txt are read by the FileReader and displayed by the paragraph as shown in the following image.

Reading from files using server-side modules

This is another way that we can use to read files using JavaScript by leveraging the node modules. In this example, we will use a file system module of the node module to read from a file on our file system.

Go to visual studio code and create a file named content.txt. Copy and paste the following text into the file.

File read using a server side module

Create another file named server.js and paste the following code into the file.

We use the require() method to retrieve the file system object by passing fs as a parameter of the method.

Call the readFile() method from the returned object and pass the file to be read, the encoding, and a callback as the parameters of the method.

The callback contains an error that may occur when reading the file and the data read from the file if there is no error.

Inside the callback function, we first check if there is an error and log it to the console. otherwise, we log the contents read from the file to the console.

Use the following command to execute the code and note that the node runtime environment must be installed on your computer before executing the code.

~/Documents/project$ node server.js

output:

File read using a server side module

Writing to files using a server-side module

This is the final approach that we are going to cover in this article. This method is the same as the above but with a few differences.

We will use the server.js file and content.txt files that we have created in the previous example. Clear the contents of the JavaScript file and paste the following code into the file.

Call the writeFile() method from the file system object returned by the require() method and pass the file name, the data to be written to the file, and a callback as the parameters of the method.

We have created a string to hold the data to be written to the file. The callback function of the writeFile() method has only one parameter that contains an error that might occur when we try to write to the file.

Use the same command we used in the previous example to execute this code. The string we created in the content.txt file is overwritten with a new string that we have defined in the writeFile() method.

If you open the content.txt file, you will find that it has been overwritten with the following text.

File written using a server side module

Conclusion

In this tutorial, we have learned how to read and write from files in JavaScript by using the ActiveXObject available in internet explorer, using FileReader API to read from files, and finally using server-side libraries with node to read and write from files. The main point to note in this tutorial is that browsers should not access the user's file system as it is considered a bad practice and also leads to security issues

Top comments (0)