JavaScript | Program to write data in a text File
Pre-requisite: How to import a library in JavaScript. Read from here: https://www.geeksforgeeks.org/javascript-importing-and-exporting-modules/ .
There is a built-in Module or in-built library in NodeJs which handles all the writing operations called fs (File-System). It is basically a JavaScript program (fs.js) where function for writing operations is written. Import fs-module in the program and use functions to write text to files in the system. The following function will create a new file with a given name if there isn’t one, else it will rewrite the file erasing all the previous data in it.
Used Function: The writeFile() functions is used for writing operation.
Syntax:
writeFile( Path, Data, Callback)
Parameters: This method accepts three parameters as mentioned above and described below:
- Path: It takes in relative path from the program to the text File. If the file is to be created in the same folder as that of the program, then give the name of the file only. If file not exists then new file will be created automatically.
- Data: This argument takes in data which need to write in the file.
- Callback Function: It is the callback function which further has an argument (err). If the operation fails to write the data, err shows the fault.
Example:
<script> // Requiring fs module in which // writeFile function is defined. const fs = require('fs') // Data which will write in a file. let data = "Learning how to write in a file." // Write data in 'Output.txt' . fs.writeFile('Output.txt', data, (err) => { // In case of a error throw err. if (err) throw err; }) </script> |
Output:
Learning how to write in a file.
Note: Above script can be run using NodeJs interpreter in terminal.
Recommended Posts:
- Javascript | Program to read text File
- How to select all text in HTML text input when clicked using JavaScript?
- JavaScript | WebAPI | File | File.size Property
- JavaScript | WebAPI | File | File.type Property
- JavaScript | WebAPI | File | File.name Property
- How to include a JavaScript file in another JavaScript file ?
- How to write an inline IF statement in JavaScript ?
- How to copy the text to the clipboard in JavaScript?
- How to get the value of text input field using JavaScript?
- How to change the text of a label using JavaScript ?
- How to remove text from a string in JavaScript?
- How to get the Highlighted/Selected text in JavaScript?
- Calculate the width of the text in JavaScript
- JavaScript | Get the text of a span element
- How to process each letter of text using JavaScript ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



