In this article, we are going to talk about how to read or write text to a file in JavaScript. If you are a JavaScript developer you know that one cannot save a file locally as it can create massive security problems.

Another method would be saving the file on our server. For this, we have to pass all the text data in our file to our server. After this, we have to use the server-related server-side language due to which we will be able to execute the written code in the file. Apart from this, we can also store the file on the client-side. An example would be using cookies to store the information.

JavaScript does not hold the ability to access the user’s file system which is why we have to run the project on a server. To do this we will be using node.js which will aid us as we can use its built-in module or the library. We can use this to provide a download link of the text file for the users

Prerequisite: How to import a library in JavaScript

NodeJs provides us with a module or a library that handles everything related to write operations in JavaScript. It is known as “browserify-fs”. In simple words, we can say that “browserify-fs” is a JavaScript program where all the functions are written for writing operations.

Let’s install browserify with the following command:

> npm install browserifyfs

When it is installed successfully, import the browserify-fs module in the required program. We can now use different functions to write texts or read texts from a file.

Write to File

Let’s look at an example of a function that will create a new file with the specified name. If there already exists a file with that specific name then all of its data will be erased and rewritten.

writeFile( Path_to_file, Data_tobewritten, Callback_function)

The writeFile function is used for writing operations in Node; it accepts three different parameters as mentioned. Let’s look at them in a little depth:

Path: It is basically the location or relative path to the text file where you want to create or rewrite a file. We can also just provide the name of a file and the file will be generated in the same folder as the program.

Data: The data that is written to the file goes here.

Callback Function: This parameter is very helpful as for example for some reason the operation did not write our data then it will generate an error and show us the error. It has an argument where we can pass the error string or the error argument.

Demonstration of writing text into a file::

For writing text into the file, first, we have to require the “browserify-fs” module which includes the function definition of the writeFile() function.

// Require browserify-fs which includes writefile() function

const fs = require(‘browserify-fs’)

Later, let’s create a variable with the name of data in which we will have some string data to which we want to store into a file.

// a simple text to write into the file

let data = “Hello and Welcome to linuxhint.com”

Now, access the writeFile function, provide it the file name along with the data you want to store into the file, and write an error handler callback function as shown below:

// Writing data into the ‘file.txt’ file

fs.writeFile(‘file.txt’, data, (err) => {

// error handling using throw

if (err) throw err;

})

After completing the code for writing some data into the file, the whole code snippet will look exactly like this:

// Require browserify-fs which includes writefile() function

const fs = require(‘browserify-fs’)

// a simple text to write into the file

let data = “Hello and Welcome to linuxhint.com”

// Writing data into the ‘file.txt’ file

fs.writeFile(‘file.txt’, data, (err) => {

// error handling using throw

if (err) throw err;

})

Once all the code is written and when you will execute the above-given code, it will create a file in the browser. Now, let’s verify it by reading the same file.

Read File

Now that we have written to a file, let’s read from a file. The function readFile() is used when we want to read the content of some file.

Syntax:

readFile( Path_to_file, Options, Callback_function)

The readFile() function is used for reading operations; it also accepts three parameters as mentioned above. Let’s look at them in a little depth:

path: Just like in writeFile(), the readFile() path parameter is also to specify the location of the file. Suppose we are and the program is in the same file then we have to just specify the file name and not the path we want to read.

Options: An optional parameter/argument that specifies the data that is to be read from the text file. The default buffer is used, If no argument is passed.

Callback Function: It is the function that further has two different arguments. These arguments are err and data. If the operation is not successful in extracting the data from the file then the err shows what the fault is, else if the operation is successful then the data argument has the data from the file.

Demonstration of reading text from a file

We will use the recently created file file “file.txt”.

file.txt data: “Hello and Welcome to linuxhint.com”

For reading text from the file, first, we will require the “browserify-fs” module which includes the function definition of the readFile() function.

// Require browserify-fs which includes readfile() function

const fs = require(‘browserify-fs’)

Then, we will access the readFile() function, provide it the file name you want to read data from, and write a callback function for error handling and showing data:

// Reading data from the ‘file.txt’ file

fs.readFile(‘file.txt’, (err, data) => {

// error handling using throw

if (err) throw err;

// showing fetched data from the file onto the console

console.log(data.toString());

})

After completing the code for reading the data from the file, the whole code snippet will look exactly like this:

// Require browserify-fs which includes readfile() function

const fs = require(‘browserify-fs’)

// Reading data from the ‘file.txt’ file

fs.readFile(‘file.txt’, (err, data) => {

// error handling using throw

if (err) throw err;

// showing fetched data from the file onto the console

console.log(data.toString());

})

Once all the code is written and when you will execute the above-given code, it will read the desired file from the browser and show all the data on the console, as shown in the screenshot given below:

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/09/echo/word-image-138.png" data-lazy- height="79" src="data:image/svg xml,” width=”721″>

This is how you can read/write data into a file using the browserify-fs module in javaScript.

Conclusion

Writing or reading a file in any programming language is a necessity as we can develop small projects where we don’t need large databases. We then use file systems to read or write data to a file. In this article, we saw how to read or write text into a file in JavaScript. We used “browserify-fs” to achieve our task.

About the author

<img data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2021/09/echo/7011409B3A384F43A8417D1DAC68D179-150×150.jpg613984f3d203f.jpg" height="112" src="data:image/svg xml,” width=”112″>

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.