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
- To use the module in Node.js, use the require() function.
- We created a variable named fs using const. One can also use let and other keywords for the same.
- Then another variable data is created using let. Here a plain text file is stored.
- 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.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.