Is it possible to write data to file using only JavaScript?


In this tutorial, we will learn if it is possible to write data to files using only JavaScript.

JavaScript has a library named fs (short form of File-System) that manages all writing operations. It is a JavaScript program (fs.js) with functions for writing operations. Utilize functions to write text to system files by importing the fs module into the program. For example, the writeFile() function will erase all old data from a file and create a new one with the specified name if there isn’t already one. It is mainly used for writing operations.

The File-System module is a handy tool for writing data in the file. It also has other methods to make operations in the files, such as reading the file, appending some text, etc. The syntax of the file system module is very user-friendly. To write some data in the file, we need to mention the file path, the data, and a callback function to handle errors.

Users can follow the below syntax to create a Script tag.

Syntax

//syntax to use writeFile function
fs.writeFile(FilePath, FileData, Callback)

In the above syntax, fs is the file-system module object.

Parameters

  • FilePath − The application accepts a relative path to the text file. Give the file's name if it is intended to be produced in the same folder as the program. If the file doesn't already exist, a new one will be generated automatically.

  • FileData − This argument accepts data that must be written to a file.

  • Callback Function − There is an argument in the callback function (err). Err displays the fault if the operation fails to write the data successfully.

Example

In this example, we have used the writeFile method of the file system library to write something to a file using JavaScript. The code file needs to be saved as a ‘.js’ extension. To execute this file, we need to write ‘node <file_name>.js’ on the system’s terminal. We will write an email id on a text file using the fs module. After executing the code, the users can open the text file and verify it on their system.

// importing the 'fs' module
const fs = require('fs')

// Data (email ID) which will write in a file.
let data = "tutorialspoint@tutorialspoint.com"

// Write data in 'myfile.txt'.
fs.writeFile('myfile.txt', data, (err) => {
   
   // if any error occurs, then throw it on the terminal
   if (err) throw err;
})

Output


In this tutorial, we learned whether writing data to a file using only JavaScript is possible. In addition, we learned about the file system module, the syntax, and an example. In the example, we write on a file using the writeFile method of fs (file system). Users can follow the example to understand the functionality better.

Updated on: 06-Dec-2022

332 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements