How to operate callback based fs.writeFile() method with promises in Node.js ?
Last Updated :
18 Jul, 2020
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
javascript
// 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}`)
})
Implementing the same functionality using async-await.
javascript
// 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}`)
})
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
javascript
// 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}`);
})
Implementing the same functionality using async-await.
javascript
// 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}`);
});
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:
Similar Reads
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
REST API Introduction REST API stands for REpresentational State Transfer API. It is a type of API (Application Programming Interface) that allows communication between different systems over the internet. REST APIs work by sending requests and receiving responses, typically in JSON format, between the client and server.
7 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
Top 10 Projects For Beginners To Practice HTML and CSS Skills Learning to code is an exciting journey, especially when stepping into the world of programming with HTML and CSSâthe foundation of every website you see today. For most beginners, these two building blocks are the perfect starting point to explore the creative side of web development, designing vis
8 min read