Node.js filehandle.writeFile() Method from class: FileHandle
The filehandle.writeFile() method is used to define in the File System module of Node.js. The File System module basically interacts 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 that will write to the file.
- options: It is an optional parameter that affects the output in some way accordingly we provide it to the function call or not.
- encoding: It is a string that specifies the encoding technique, the default value is ‘utf8’.
Example 1: This example explains how to write operations done to the file that already exists.
javascript
const fs = require( 'fs' )
const 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' )
await filehandle.writeFile(data)
} finally {
if (filehandle) {
await filehandle.close();
}
}
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 operations done to the file that did not exist earlier but was created at run time.
javascript
const fs = require( 'fs' )
const writeToFile = async (path, data) => {
let filehandle = null
try {
filehandle = await fs
.promises.open(path, mode = 'w' )
await filehandle.writeFile(data)
} finally {
if (filehandle) {
await filehandle.close();
}
}
const buff = fs.readFileSync(path)
const content = buff.toString()
console.log(`\nContents of the file :\n${content}`)
}
let 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:
Last Updated :
06 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...