Open In App

JavaScript Program to write data in a text File

Last Updated : 21 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to learn how can we write data in a text file. There is a built-in Module or in-built library in NodeJs that handles all the writing operations called fs (File-System). It is basically a JavaScript program (fs.js) where a function for writing operations is written. Import fs-module in the program and use functions to write text to files in the system.

Used Function:

The writeFile() functions is used for writing operations. 

Pre-requisites:

Syntax:

writeFile( Path, Data, Callback)

Parameters:

  • Path: It takes in the 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 the file does not exist then a new file will be created automatically.
  • Data: This argument takes in data that needs to be written in the file.
  • Callback Function: It is the callback function that further has an argument (err). If the operation fails to write the data, an error shows the fault.

Example 1: The ouput will be in a separate file name “Output.txt”.

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: The ouput will be in a separate file name “Hello.txt”.

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: Example 3: Appending data to an existing file.

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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads