Skip to content
Related Articles

Related Articles

How to operate callback based fs.appendFile() method with promises in Node.js ?
  • Last Updated : 14 Jul, 2020

The fs.appendFile() method is 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 appendFile() method is used to append new data in the existing file or if the file does not exist then the file is created first and after that given data is appended to it.

The fs.appendFile() method is based on callback. Using callback methods leads to a great chance of callback nesting or callback hell problems. Thus to avoid it we almost like to work with a promise-based method. Using some extra node.js method, we can operate a callback-based method in promise way.

Syntax:

fs.appendFile(path, data, options)

Parameter:

  • path: It is a String, Buffer or URL that specifies the path to the target file in which given data is to be appended.
  • data: It is a String or Buffer that is going to append to the target file.
  • options: It is an optional parameter which affects the output in someway accordingly we provide it to the function call or not.
    • encoding: It specifies the encoding technique, default is ‘UTF8’.
    • mode: It specifies the file mode. File modes allow us to create, read, write, or modify a file. The default value is ‘0o666’.
    • flag: It specifies the flag used while appending to the file. The default value is ‘a’.

Approach: The fs.appendFile() method based on callback. To operate it with promises, first, we use promisify() method defined in the utilities module to convert it into a promise based method.



Example 1:




// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
  
// Convert callback based methods to
// promise based methods
const appendContent = util.promisify(fs.appendFile)
const readFileContent = util.promisify(fs.readFile)
   
  
// The readFileContent() method reads the
// file and returns buffer form of the data 
readFileContent('./testFile.txt')
.then(buff => {
  
    // File content before append 
    const oldContent = buff.toString()
    console.log(`\nBefore Append: ${oldContent}\n`)
   
    // Append operation
    return appendContent('./testFile.txt'
            '\nHey, I am newly added..!!')
})
   
.then(() => {
  
    // Getting new file content
    return readFileContent('./testFile.txt')
})
     
.then(buff => {
  
    // File content after append 
    const newContent = buff.toString()
    console.log(`After Append: ${newContent}\n`)
})
     
.catch(err => {
  console.log(`Error Occurs, 
    Error code -> ${err.code}, 
    Error NO -> ${err.errno}`)
})

Implementing the same functionality using async-await.




// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
  
// Convert callback based methods to
// promise based methods
const appendContent = util.promisify(fs.appendFile)
const readFileContent = util.promisify(fs.readFile)
   
const appendDataToFile = async (path, data) => {
   
  // The readFileContent() method reads the file
  // and returns buffer form of the data 
  const oldBuffer = await readFileContent(path)
   
  // File content before append 
  const oldContent = oldBuffer.toString()
   
  // Append operation
  await appendContent(path, data)
   
  const newBuffer = await readFileContent(path)
   
  // File content after append 
  const newContent = newBuffer.toString()
   
  console.log(`\nBefore Append: ${oldContent}\n`)
  console.log(`After Append: ${newContent}`)
}
   
appendDataToFile('./testFile.txt'
    '\nHey, I am newly added..!!')
.catch(err => {
  console.log(`Error Occurs, 
    Error code -> ${err.code}, 
    Error NO -> ${err.errno}`)
})
})

Output:

Example 2: When a given path to the filename does not exist.




// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
  
// Convert callback based methods to 
// promise based methods
const appendContent = util.promisify(fs.appendFile)
const readFileContent = util.promisify(fs.readFile)
  
// Append operation if given file does not exist
// it will be created first then data is appended
appendContent('./testFile.txt'
    'Please add me to the test file..!!')
.then(() => {
  
    // readFileContent() method reads the file
    // and returns buffer form of the data 
    return readFileContent('./testFile.txt')
})
   
.then(buff => {
  
    // Appended data
    const content = buff.toString()
    console.log(`\nContent : ${content}`)
})
   
.catch(err => {
  console.log(`Error Occurs, 
    Error code -> ${err.code}, 
    Error NO -> ${err.errno}`)
})

Implementing the same functionality as async-await.




// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
  
// Convert callback based methods to 
// promise based methods
const appendContent = util.promisify(fs.appendFile)
const readFileContent = util.promisify(fs.readFile)
  
const appendDataToFile = async (path, data) => {
  
  // Append operation if given file does not exist
  // it will created first then data is appended
  await appendContent(path, data)
   
  // readFile() method reads the file
  // and returns buffer form of the data 
  const buff = await readFileContent(path)
   
  // File content after append 
  const content = buff.toString()
  console.log(`\nContent : ${content}`)
}
   
appendDataToFile('./testFile.txt'
    'Please add me to the test file..!!')
  
.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:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :