How to write a file in JavaScript

How to write a file in JavaScriptHey Geeks, in this article we are gonna talk about how you can write a file in JavaScript. As a developer saving a sensitive file locally is not secure, to make this secure we need to save the file in some server, for this, we need to save all the data of file in our server. Now when the file is in our server we need some server side scripting language commands to manipulate the files and data through the server.

We are going to look two methods by which we can write a file in JavaScript. One is using NodeJS in-built library and the other one is using PHP on top of JavaScript.

  1. Using NodeJS built-in Library
  2. Using PHP in JavaScript

How to Write a file in JavaScript

Using NodeJS built-in Library

NodeJS contains a library which is a program ‘fs.js’, this library is help full in reading and writing files in JavaScript. Here fs stands for File-system. With the help of this file-system module in JavaScript, reading and writing operation can be performed both in synchronous and asynchronous manner.

To write a file in JavaScript we have writeFile() method in fs.js library.

Syntax:

writeFile(path, data, callback)

Parameters:

writeFile() method has 3 parameters Path, data and callback as given above.

  • Path: Here we provide the location where we want the text file to be generated. In case if you want to generate the file at same location where the program is stored just put the name of file instead of the whole path.
  • Data: This is the text content or data that we need to store in the file. This could be a pre declared variable.
  • Callback: This is a callback function which has an argument (err), if for any reason our program fails to write data in the file, an error log will be shown to you.

Example(Source Code):

<script >
    const fs = require('fs') 
    let data = "Hello and Welcome to GeekyBeginners.com"
    fs.writeFile('output.txt', data, (err) => {
    if (err) throw err;
}) < /script>

Output

Hello and Welcome to GeekyBeginners.com

Using PHP in JavaScript

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

Example(Source Code):

<!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 
         $editFile = fopen("output.txt", "w");   //opens a new file to write
         $str = "Welcome to GeekyBeginners.com"; //string that we want to write in file.
         $editFile = fwrite($editFile, $str);  //writes the file

         $openFile = fopen("output.txt","r"); 
         $editFile = fread($openFile, filesize("output.txt"));  
      ?>
      <!--JS code-->
      <script>
          function WriteFile(){
            var file = "<?php echo $editFile ?>";
            //Reading the file
            document.write(file);
          }
      </script>

      <h1 style="text-align:center">Write Files in JavaScript using PHP</h1>
      <center><button onclick="WriteFile()">Write File</button></center>
   </body>
</html>

Output:

Welcome to GeekyBeginners.com

Write-a-file-in-JavaScript-using-PHP

Explanation:

In this example code, we have used PHP code inside JavaScript code. We have created a variable in PHP ‘editFile’ and opened a file ‘output.txt’ in write mode. We have declared a variable ‘str’ to which we are assigning the string that we need to pass inside the output.txt file.

Then inside JavaScript tag we have created a function WriteFile() which has a variable ‘file’ getting the data from PHP code. And then we are writing the file variable content to the output.txt file using document.write() function.

Conclusion

So these are two basic methods by which we can write a file in JavaScript. I hope both of the methods explained here are easy to understand. If you have still any doubt or questions regarding both the explanation feel free to write a comment. Our team will assist you shortly.

Write for us
GeekyBeginners articles are written by software geeks like you. If you also would like to contribute to GeekyBeginners by writing paid articles, you can check the write for us page.

Leave a Comment