How to Write a File in JavaScript

We know that we cannot read or write files in Javascript on the client-side browsers. But using the fs module of Node.js, we can carry this functionality on the server-side. In this post, we will learn, How we can write files in Javascript with the help of node.js.

Fs(File-System) is a library of Node.js used to manage all read and write operations. With the help of fs(File-System), module reading and writing files can be done synchronous and asynchronous. This article will discuss the Javascript program that contains a function for writing operations.

There are specific ways by which we can write a file in Javascript. Some we are discussing in this article.

How to Write a File in JavaScript

To write a file in JavaScript, use the writeFile() method of the fs(File-System) module. The fs.writeFile() is a Node.js method used to write the specified data to a file asynchronously. By default, the file would be replaced if it exists.

Syntax

writeFile(Path, Data, callback)

Parameters

The writeFile() method accepts three parameters: path, data, and callback.

  • path: This is the location of the Text file. If you want to generate the file at the same location where your program is stored, then, in this case, provide the name of the file only.
  • data: In this, we need to provide the content that needs to be stored in the file.
  • callback: This callback function argues (err) that if the operation fails to write data in the file, an error log will be shown to you.

Example

Create an app.js file and add the following code inside it.

const fs = require('fs')

let data = "How to write a file in Javascript."
fs.writeFile('output.txt', data, (err) => {
 if (err) throw err;
});

Output

    It will create an output.txt file that has the following content in it.

    How to write a file in Javascript.

    Explanation

    1. To use the module in Node.js, use the require() function.
    2. We created a variable named fs using const. One can also use let and other keywords for the same.
    3. Then another variable data is created using let. Here a plain text file is stored.
    4. A function called writeFile() is created, which generates the texts within the data variable.

    You can see that we wrote a file using the fs.writeFile() function.

    How to read file content using PHP fread()

    Using PHP can be another approach to writing a file in Javascript. We use some built-in Javascript functions to read and write files. Some built-in functions like fopen(), fread() and fwrite(), we will be using here. The fopen() function takes two arguments, Path and mode(0 for reading a file and 3 for writing a file), and returns -1 if the file is successfully opened.

    To open a file use fopen() function

    openFile = fopen(getFilePath(), 0);
    

    Explanation

    The function fopen() takes two parameters(path and mode). Here mode value 0 is used for reading and 3 for writing the file. This function will then return -1 if the file is successfully opened.

    To read the file content, use the fread() Method

    readString = fread(openFile,flength(file));

    Explanation

    The function fread() also takes two parameters(opened file and length of file). Therefore, the function will help read the contents of the files present on the user’s computer.

    Use the fwrite() Method to write the contents in the file

    editFile = fopen("c:\output.txt", 3);
    fwrite(file, str);

    Explanation

    The fwrite() function is used to edit or modify the file’s contents. For example, in the above code, the content of readString will be written to editFile using fwrite(editfile, readString).

    Below is a program that demonstrates the usage of the above methods in PHP.

    <!DOCTYPE html>
    <html lang="en">
     <head>
       <meta charset="UTF-8">
       <meta http-equiv="X-UA-Compatible" content="IE=edge">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>Writing Files in JavaScript</title>
     </head>
     <body>
     <!--php code-->
       <?php 
         $openFile = fopen("read_me.txt","r"); //The code opens the file
         $readString = fread($openFile, filesize("read_me.txt")); //read the file from the user system 
         $editFile = fopen("output.txt", "w"); //opens a new file with write access
         $str = "this is the text that will be added to the file."; //string that we want to write in file.
         $editFile = fwrite($editFile, $str); //writes the file
       ?>
       <!--JS code-->
       <script>
         var file = "<?php echo $readString ?>";
         // Reading the file
         document.write(file);
       </script>
     </body>
    </html>
    

    Output

    This is the text that will be displayed.

    Note: In the program, the “output.txt” file is opened. The program will display whatever is present in the file. In this case, the text that is present is as follows:

    This is the text that will be displayed.

    Hence this text file will be generated as the output.

    That’s it for this tutorial.

    See also

    How to Read a JSON file in JavaScript

    JavaScript import vs. require

    Leave a Comment