Node.js filehandle.writeFile() Method from class: FileHandle - GeeksforGeeks

29 Jun, 2020
The filehandle.writeFile() method is used to defined in the File System module of Node.js. The File System module is basically to interact with the hard disk of the user’s computer. The fs.writeFile() method asynchronously writes data to a file, replacing the file if it already exists.
Syntax:
filehandle.writeFile(data, options)
Parameter: This method accepts two parameters as mentioned above and described below:
data: It is a String, Buffer or Uint8Array instance. It is the data which will write to the file.
options: It is an optional parameter that affects the output in someway accordingly we provide it to the function call or not.encoding: It is a string that specifies the encoding technique, default value is ‘utf8’.
encoding: It is a string that specifies the encoding technique, default value is ‘utf8’.
Example 1: This example explains how to write operation done to the file that already exists.
// Node.js program to demonstrate the// filehandle.writeFile() Method  // Importing File System and Utilities moduleconst fs = require('fs')  // The readFileSync() method reads the// contents of the file and returns the// buffer form of the dataconst oldBuff = fs.readFileSync('./tesTfile.txt')const oldContent = oldBuff.toString()console.log(`\nOld content of the file :\n${oldContent}`)  const writeToFile = async (path, data) => {    let filehandle = null      try {        filehandle = await fs.promises.open(path, mode = 'w')        // Write to file        await filehandle.writeFile(data)    } finally {        if (filehandle) {            // Close the file if it is opened.            await filehandle.close();        }    }    // New content after write operation    const newBuff = fs.readFileSync('./tesTfile.txt')    const newContent = newBuff.toString()    console.log(`\nNew content of the file :\n${newContent}`)}  writeToFile('./testFile.txt', "Hey, I am newly added!")    .catch(err => {        console.log(`Error Occurs, Error code ->             ${err.code}, Error NO -> ${err.errno}`)    })
Output:
Example 2: This example explains how to write operation done to the file that not exist earlier but created at run time.
// Node.js program to demonstrate the// filehandle.writeFile() Method  // Importing File System and Utilities moduleconst fs = require('fs')  const writeToFile = async (path, data) => {    let filehandle = null      try {        filehandle = await fs            .promises.open(path, mode = 'w')        // Write to file        await filehandle.writeFile(data)    } finally {        if (filehandle) {            // Close the file if it is opened.            await filehandle.close();        }    }    // The readFileSync() method reads    // the contents of the file and     // returns the buffer form of the data    const buff = fs.readFileSync(path)    const content = buff.toString()    console.log(`\nContents of the file :\n${content}`)}  var query = "Hey there, I am newly added "        + "content of newly added file!";writeToFile('./testFile.txt', query)    .catch(err => {        console.log(`Error Occurs, Error code ->         ${err.code}, Error NO -> ${err.errno}`)    })
Directory structure before running the program:
Directory structure after running the program:
Output:
Node.js-fs-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Mongoose | findByIdAndUpdate() Function
Express.js res.render() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript