JavaScript Program to write data in a text File (original) (raw)

Last Updated : 09 Jan, 2025

**To write data to a text file using JavaScript in a Node.js environment, the built-in fs (File System) module provides efficient file operations. It supports reading, writing, appending, and deleting files, making it a powerful tool for handling file-related tasks in Node.js.

**Used Function:

The writeFile() functions is used for writing operations.

**Pre-requisites:

**Syntax:

writeFile( Path, Data, Callback)

**Parameters:

**Example 1: This Node.js script uses the fs module to write the string "Learning how to write in a file." into a file named Output.txt, handling errors if they occur.

javascript `

// 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;

})

`

**Output:

Learning how to write in a file.

**Example 2: This Node.js script uses the fs module to write the string "Hello world." into a file named Hello.txt, while handling potential errors with a callback function.

JavaScript `

// Requiring fs module in which // writeFile function is defined. const fs = require('fs')

// Data which will write in a file. let data = "Hello world."

// Write data in 'Hello.txt' . fs.writeFile('Hello.txt', data, (err) => {

// In case of a error throw err.
if (err) throw err;

})

`

**Output:

Hello world.

**Example 3: This Node.js script uses the fs module's appendFile method to add the string "\nThis is some additional text." to the existing file Hello.txt, handling potential errors.

JavaScript `

// Requiring fs module in which // writeFile function is defined. const fs = require('fs')

// Data which will be appended to the file. let newData = "\nThis is some additional text."

// Append data to 'Hello.txt' . fs.appendFile('Hello.txt', newData, (err) => {

// In case of a error throw err.
if (err) throw err;

})

`

**Note: Above script can be run using the NodeJs interpreter in the terminal.

Conclusion

In conclusion, the fs module in Node.js provides a simple and efficient way to handle file operations like writing, reading, and appending data. With easy-to-use functions like writeFile() and appendFile(), managing files becomes straightforward and reliable.