How to operate callback based fs.writeFile() method with promises in Node.js ?

The fs.writeFile() is a method 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.

The fs.writeFile() 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 always like to work with a promise-based method. Using some extra node.js methods we can operate a callback-based method in promise way.

Syntax:

fs.writeFile(path, data, options)

Note: Callback not required since we operate the method with promises.

Parameters: Accepts three parameter path, data and options. The options is an optional parameter.



  • path: It is a String, Buffer or URL that specifies the path to the file where write operation is to be done.
  • data: It is string 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’.
    • mode: It is an integer value that specifies the file mode. The default value is 0o666.
    • flag: It is a string that specifies the file system flags. Default value is ‘w’.

Approach: The fs.writeFile() 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: Filename: index.js

filter_none

edit
close

play_arrow

link
brightness_4
code

// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
  
// Convert callback based methods to 
// promise based methods
const writeFile = util.promisify(fs.writeFile)
const readFile = util.promisify(fs.readFile)
  
// The readFile method read the contents of
// the file and returns the buffer form of
// the data
readFile('./testFile.txt')
.then(buff => {
  const oldContent = buff.toString()
  console.log(`\nOld content of the file 
                     :\n${oldContent}`)
  
  // The writeFile method write to the file
  // If is already exist, replaces the file
  return writeFile('./testFile.txt'
        "Hey, I am newly added!")
})
  
.then(() => {
  
  // Fetching contents of the file
  // after write operation
  return readFile('./testFile.txt')
})
  
.then(buff => {
  const newContent = buff.toString()
  console.log(`\nNew content of the 
            file :\n${newContent}`)
})
  
// If promise get rejected
.catch(err => {
   console.log(`\nError Occurs, 
          Error code -> ${err.code}, 
   Error NO -> ${err.errno}`)
})

chevron_right


Implementing the same functionality using async-await.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
  
// Convert callback based methods to 
// promise based methods
const writeFile = util.promisify(fs.writeFile)
const readFile = util.promisify(fs.readFile)
  
const writeFileContent = async (path, data) => {
  
  // The readFile method read the contents
  // of the file and returns the buffer 
  // form of the data
  const oldBuff = await readFile(path)
  const oldContent = oldBuff.toString()
  console.log(`\nOld content of the 
             file :\n${oldContent}`)
  
  // The writeFile method write to the file
  // If is already exist, replaces the file
  await writeFile(path, data)
  
  // Fetching contentsof the file after 
  // write operation
  const newBuff = await readFile(path)
    
  const newContent = newBuff.toString()
  console.log(`\nNew content of the 
             file :\n${newContent}`)
}
   
writeFileContent('./testFile.txt'
          "Hey, I am newly added!")
  
// If promise get rejected
.catch(err => {
  console.log(`\nError Occurs, 
    Error code -> ${err.code},
    Error NO -> ${err.errno}`)
})

chevron_right


Run the index.js file using the following command:

node index.js

Output:

Example 2: When given path to the file does not exist.
Filename: index.js

filter_none

edit
close

play_arrow

link
brightness_4
code

// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
  
// convert callback based methods to 
// promise based methods
const writeFile = util.promisify(fs.writeFile)
const readFile = util.promisify(fs.readFile)
  
// The writeFile method write to the file if
// the file does not exist, creates the file
// and then write to the file
writeFile('./testFile.txt'
"Hey there, I am newly added content of newly added file!")
.then(() => {
  
  // The readFile method read the contents of the file
  // and returns the buffer form of the data
  
  // Fetching contents of the file after write operation
  return readFile('./testFile.txt')
})
  
.then(buff => {
  const content = buff.toString()
  console.log(`\nContents of the file :\n${content}`)
})
  
// If promise get rejected
.catch(err => {
  console.log(`\nError Occurs, Error code -> ${err.code},
  Error NO -> ${err.errno}`);
})

chevron_right


Implementing the same functionality using async-await.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
  
// Convert callback based methods to 
// promise based methods
const writeFile = util.promisify(fs.writeFile)
const readFile = util.promisify(fs.readFile)
  
const writeFileContent = async (path, data) => {
  
  // The writeFile method write to the file
  // If the file does not exist, creates the
  // file and then write to the file
  writeFile(path, data)
  
  // The readFile method read the contents of
  // the file and returns the buffer form of
  // the data
  const buff = await readFile(path)
    
  const content = buff.toString()
  console.log(`\nContents of the file :\n${content}`)
}
   
writeFileContent('./testFile.txt'
"Hey there, I am newly added content of"
           + " newly added file!")
  
// If promise get rejected
.catch(err => {
  console.log(`\nError Occurs, 
    Error code -> ${err.code},
    Error NO -> ${err.errno}`);
});

chevron_right


Run the index.js file using the following command:

node index.js

Directory structure before running the program:

Directory structure after running the program:

Output:




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.