How to Write a File in JavaScript

To write a file in JavaScript, you can 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 existed.

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 file’s name only.
  • data: In this, we need to provide the content that needs to be stored in the file.
  • callback: This 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.

    That’s it.

    Leave a Comment