Open In App

JavaScript Program to write data in a text File

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:

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




// 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”.




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

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


Article Tags :