How to read and write files in JavaScript
Tags: javascript, webdev, computerscience, tutorial
Published: 2022-06-23 04:20:47

> Article was originally posted on [realjavascriptproject.com](https://realjavascriptproject.com/how-to-read-and-write-into-files-in-javascript/)

<!-- wp:paragraph -->
<p>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.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The data being operated on by these programs can be of varying types and formats such as text, JSON, XML, and others.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>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.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>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.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In this tutorial, we will learn the different ways that we can leverage to read and write data into a file using JavaScript.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2><a href="https://dev.to/new#a-common-bad-practice-while-using-clientside-javascript"></a>A Common bad practice while using client-side JavaScript</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>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.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>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.</p>
<!-- /wp:paragraph -->

<!-- wp:quote -->
<blockquote class="wp-block-quote"><p>Internet Explorer might be dead, however you might find the below useful</p></blockquote>
<!-- /wp:quote -->

<!-- wp:paragraph -->
<p>Internet explorer has an API named&nbsp;<code>ActiveXObject</code>&nbsp;that we can use to get a&nbsp;<code>FileSystemObject</code>&nbsp;to read and write on files. We are going to see this functionality in action in the next section.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>There are other alternatives that we can use to realize this functionality such as: using&nbsp;<code>FileReader</code>&nbsp;to read from files and using server-side libraries with runtime environments such as&nbsp;<code>node</code>.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2><a href="https://dev.to/new#writing-to-files-in-internet-explorer-using-an-raw-activexobject-endraw-"></a>Writing to files in internet explorer using an&nbsp;ActiveXObject.</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The&nbsp;<code>ActiveXObject</code>&nbsp;API is only available in internet explorer and is executed using the internet explorer console.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>To open the internet explorer console, right-click on the browser and select the option labeled&nbsp;<code>view source</code>, alternatively you can press the&nbsp;<code>F12</code>&nbsp;button on your computer keyboard.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Select the option labeled&nbsp;<code>Console</code>&nbsp;on the window that opens to open the editor where we will write our code.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Copy and paste the following code into the console.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
{% embed https://gist.github.com/rahulbanerjee26/38225b79df1eff662b5185189f103361
%}
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In the above code, we have created the&nbsp;<code>writeToFile()</code>&nbsp;method that accepts two parameters&nbsp;<code>path</code>&nbsp;and&nbsp;<code>data</code>. The&nbsp;<code>path</code>&nbsp;represents the location where our file will be created and the&nbsp;<code>data</code>&nbsp;represents the contents to be written in the file.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The&nbsp;<code>ActiveXObject()</code>&nbsp;method returns an object that allows us to access the file system by passing the argument&nbsp;<code>Scripting.FileSystemObject</code>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Call the&nbsp;<code>CreateTextFile()</code>&nbsp;method from the returned object and pass our&nbsp;<code>path</code>&nbsp;to this method and a second boolean parameter containing the value of&nbsp;<code>true</code>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The&nbsp;<code>true</code>&nbsp;value indicates that the existing file can be overwritten and you should change it to&nbsp;<code>false</code>&nbsp;if otherwise.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"textColor":"black"} -->
<p class="has-black-color has-text-color">The&nbsp;<code>CreateTextFile()</code>&nbsp;method returns a&nbsp;<code>TextStream</code>&nbsp;that allows us to write to the file. Call the&nbsp;<code>Write()</code>&nbsp;method on the returned&nbsp;<code>TextStrem</code>&nbsp;object and pass our&nbsp;<code>data</code>&nbsp;to this method to write it to the file.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Finally, call your custom function&nbsp;<code>writeToFile()</code>&nbsp;and pass the concrete details regarding the path and the data.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>To execute the code, press the run button located on the bottom right section of the console window as shown in the following image.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":56,"sizeSlug":"full","linkDestination":"custom"} -->
<figure class="wp-block-image size-full"><img src="https://realjavascriptproject.com/wp-content/uploads/2022/06/write-to-file.png" alt="" class="wp-image-56"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>The following image verifies that a file named&nbsp;<code>theFile.txt</code>&nbsp;was created under local disk&nbsp;<code>C</code>&nbsp;and a text containing the value&nbsp;<code>This text was written using a TextStream</code>&nbsp;written into it.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":57,"sizeSlug":"large","linkDestination":"custom"} -->
<figure class="wp-block-image size-large"><img src="https://realjavascriptproject.com/wp-content/uploads/2022/06/theFile-1024x575.png" alt="" class="wp-image-57"/></figure>
<!-- /wp:image -->

<!-- wp:heading -->
<h2><a href="https://dev.to/new#reading-from-files-in-internet-explorer-using-a-raw-activexobject-endraw-"></a>Reading from files in internet explorer using a&nbsp;ActiveXObject.</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>This example has the same steps as the previous one with the exception that it has its methods to read from a file.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Copy and paste the following code into the internet explorer console.</p>
<!-- /wp:paragraph -->

<!-- wp:shortcode -->
{% embed https://gist.github.com/rahulbanerjee26/145230377250948113b60f0bb7381a22 %}
<!-- /wp:shortcode -->

<!-- wp:paragraph -->
<p>In the above code, we have created a method named&nbsp;<code>readFromFile()</code>&nbsp;that accepts three parameters,&nbsp;<code>path</code>,&nbsp;<code>data</code>, and&nbsp;<code>ForReading</code>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The&nbsp;<code>ForReading</code>&nbsp;method is used to indicate that the file mode will only allow the file to be read. Other modes can be passed such as&nbsp;<code>ForWriting</code>&nbsp;and&nbsp;<code>ForAppending</code>. These modes are represented with the values&nbsp;<code>1</code>,&nbsp;<code>2</code>, and&nbsp;<code>8</code>&nbsp;respectively.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>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.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Call the&nbsp;<code>OpenTextFile()</code>&nbsp;from the object returned by&nbsp;<code>ActiveXObject()</code>&nbsp;and pass the&nbsp;<code>path</code>&nbsp;and the&nbsp;<code>ForReading</code>&nbsp;parameters in the method.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The&nbsp;<code>OpenTextFile()</code>&nbsp;method returns a&nbsp;<code>TextStream</code>&nbsp;that allows us to read from the file. Call&nbsp;<code>ReadLine()</code>&nbsp;from from the&nbsp;<code>TextStream</code>&nbsp;object to read from the file. The&nbsp;<code>ReadLine()</code>&nbsp;method will return the contents of the file as a string.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>To verify that our file was read, log the contents of the string to the console as shown in the following image.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":58,"sizeSlug":"large","linkDestination":"custom"} -->
<figure class="wp-block-image size-large"><img src="https://realjavascriptproject.com/wp-content/uploads/2022/06/read-from-file-1024x504.png" alt="" class="wp-image-58"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>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.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2><a href="https://dev.to/new#reading-from-files-using-raw-filereader-endraw-api"></a>Reading from files using&nbsp;FileReader&nbsp;API</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The&nbsp;<code>FileReader</code>&nbsp;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&nbsp;<code>input</code>&nbsp;tag.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Go to visual studio code and create a file named&nbsp;<code>index.html</code>. copy and paste the following code.</p>
<!-- /wp:paragraph -->

<!-- wp:shortcode -->
{% embed https://gist.github.com/rahulbanerjee26/9e0adc6a0a5114b2748a8f16a7a3857f %}
<!-- /wp:shortcode -->

<!-- wp:paragraph -->
<p>In the above code, we have created an HTML file that contains an input of type&nbsp;<code>file</code>&nbsp;and one paragraph.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Inside the&nbsp;<code>head</code>&nbsp;section, we have added the JavaScript code with will handle the functionality of reading the file that we select.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>To retrieve the selected file, we use the&nbsp;<code>querySelector()</code>&nbsp;method and pass the type of input as a parameter to this method.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The&nbsp;<code>readAsText()</code>&nbsp;method reads the contents of the file and returns the&nbsp;<code>result</code>&nbsp;as a string. To display this string to the browser we use the&nbsp;<code>querySelector()</code>&nbsp;and pass&nbsp;<code>class</code>&nbsp;as the parameter to this method to retrieve the paragraph and assign it the result.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Having gained access to the paragraph, we set its&nbsp;<code>innerText</code>&nbsp;value to the&nbsp;<code>result</code>&nbsp;returned by the&nbsp;<code>readAsText()</code>&nbsp;method once the file has been loaded as indicated by the&nbsp;<code>addEventListener()</code>&nbsp;method.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Create a file named&nbsp;<code>file-reader.txt</code>&nbsp;and add the text&nbsp;<code>Reading using a FileWriter</code>&nbsp;inside the file. Open the&nbsp;<code>index.html</code>&nbsp;file in any browser and press the&nbsp;<code>choose file</code>&nbsp;button to select the&nbsp;<code>file-reader.txt</code>&nbsp;file.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The contents we added in the&nbsp;<code>file-reader.txt</code>&nbsp;are read by the&nbsp;<code>FileReader</code>&nbsp;and displayed by the paragraph as shown in the following image.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":59,"sizeSlug":"large","linkDestination":"custom"} -->
<figure class="wp-block-image size-large"><img src="https://realjavascriptproject.com/wp-content/uploads/2022/06/file-reader-test-1024x123.png" alt="" class="wp-image-59"/></figure>
<!-- /wp:image -->

<!-- wp:heading -->
<h2><a href="https://dev.to/new#reading-from-files-using-serverside-modules"></a>Reading from files using server-side modules</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>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.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Go to visual studio code and create a file named&nbsp;<code>content.txt</code>. Copy and paste the following text into the file.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"backgroundColor":"black","textColor":"white"} -->
<pre class="wp-block-code has-white-color has-black-background-color has-text-color has-background"><code>File read using a server side module</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Create another file named&nbsp;<code>server.js</code>&nbsp;and paste the following code into the file.</p>
<!-- /wp:paragraph -->

<!-- wp:shortcode -->
{% embed https://gist.github.com/rahulbanerjee26/97f942b30327594d802706bc50abaa1c %}
<!-- /wp:shortcode -->

<!-- wp:paragraph -->
<p>We use the&nbsp;<code>require()</code>&nbsp;method to retrieve the file system object by passing&nbsp;<code>fs</code>&nbsp;as a parameter of the method.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Call the&nbsp;<code>readFile()</code>&nbsp;method from the returned object and pass the file to be read, the encoding, and a callback as the parameters of the method.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The callback contains an error that may occur when reading the file and the data read from the file if there is no error.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>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.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>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.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"style":{"color":{"text":"#fefefe"}},"backgroundColor":"black"} -->
<pre class="wp-block-code has-black-background-color has-text-color has-background" style="color:#fefefe"><code>~/Documents/project$ node server.js</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>output:</p>
<!-- /wp:paragraph -->

<!-- wp:code {"style":{"color":{"text":"#fefefe"}},"backgroundColor":"black"} -->
<pre class="wp-block-code has-black-background-color has-text-color has-background" style="color:#fefefe"><code>File read using a server side module</code></pre>
<!-- /wp:code -->

<!-- wp:heading -->
<h2><a href="https://dev.to/new#writing-to-files-using-a-serverside-module"></a>Writing to files using a server-side module</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>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.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We will use the&nbsp;<code>server.js</code>&nbsp;file and&nbsp;<code>content.txt</code>&nbsp;files that we have created in the previous example. Clear the contents of the JavaScript file and paste the following code into the file.</p>
<!-- /wp:paragraph -->

<!-- wp:shortcode -->
{% embed https://gist.github.com/rahulbanerjee26/c78f0339cc8e70d575dbec9edc45211d %}
<!-- /wp:shortcode -->

<!-- wp:paragraph -->
<p>Call the&nbsp;<code>writeFile()</code>&nbsp;method from the file system object returned by the&nbsp;<code>require()</code>&nbsp;method and pass the file name, the data to be written to the file, and a callback as the parameters of the method.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We have created a string to hold the data to be written to the file. The callback function of the&nbsp;<code>writeFile()</code>&nbsp;method has only one parameter that contains an error that might occur when we try to write to the file.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Use the same command we used in the previous example to execute this code. The string we created in the&nbsp;<code>content.txt</code>&nbsp;file is overwritten with a new string that we have defined in the&nbsp;<code>writeFile()</code>&nbsp;method.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>If you open the&nbsp;<code>content.txt</code>&nbsp;file, you will find that it has been overwritten with the following text.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"style":{"color":{"background":"#020202","text":"#fffefe"}}} -->
<pre class="wp-block-code has-text-color has-background" style="background-color:#020202;color:#fffefe"><code>File written using a server side module</code></pre>
<!-- /wp:code -->

<!-- wp:heading -->
<h2><a href="https://dev.to/new#conclusion"></a>Conclusion</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In this tutorial, we have learned how to read and write from files in JavaScript by using the&nbsp;<code>ActiveXObject</code>&nbsp;available in internet explorer, using&nbsp;<code>FileReader</code>&nbsp;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</p>
<!-- /wp:paragraph -->