Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How to operate callback-based fs.truncate() method with promises in Node.js ?
Next article icon

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

Last Updated : 18 Jul, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

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




// 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.




// 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




// 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.




// 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:



Next Article
How to operate callback-based fs.truncate() method with promises in Node.js ?
author
hunter__js
Improve
Article Tags :
  • Node.js
  • Web Technologies
  • Node.js-fs-module
  • Node.js-Misc

Similar Reads

  • How to operate callback-based fs.mkdir() method with promises in Node.js ?
    The fs.mkdir() 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 mkdir() method is used to asynchronously create a directory. The fs.mkdir() method is based on callback. Using callback methods leads
    4 min read
  • How to operate callback-based fs.readdir() method with promises in Node.js ?
    The fs.readdir() 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 readdir() method is used to read the contents of a directory. The fs.readdir() method is based on callback. Using callback methods l
    3 min read
  • How to operate callback-based fs.truncate() method with promises in Node.js ?
    The fs.truncate() 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 truncate() method is used to modify the inner contents of the file by ‘len’ bytes. If len is shorter than the file’s current length, t
    4 min read
  • How to operate callback-based fs.opendir() method with promises in Node.js ?
    The fs.opendir() 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 method used to asynchronously open a directory.The fs.opendir() method is based on callback. Using callback methods leads to a great
    5 min read
  • How to operate callback-based fs.rename() method with promises in Node.js ?
    The fs.rename() method is defined in the File System module of Node.js. The File System module is basically to interact with hard-disk of the user’s computer. The rename() method is used to rename the file at the given old path to a given new path. If the new path file already exists, it will be ove
    5 min read
  • How to operate callback-based fs.readFile() method with promises in Node.js ?
    The fs.readFile() 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 readFile() method is used to asynchronously read the entire contents of a file and returns the buffer form of the data. The fs.read
    5 min read
  • How to operate callback based fs.appendFile() method with promises in Node.js ?
    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
    4 min read
  • How to convert function call with two callbacks promise in Node.js ?
    Promise: Promise is used to handle the result, if it gets the required output then it executes the code of then block, and if it gets the error then it executes the code of the catch block. A promise looks like this - function() .then(data => { // After promise is fulfilled console.log(data); })
    3 min read
  • How to Convert an Existing Callback to a Promise in Node.js ?
    Node.js, by nature, uses an asynchronous, non-blocking I/O model, which often involves the use of callbacks. While callbacks are effective, they can lead to complex and hard-to-read code, especially in cases of nested callbacks, commonly known as "callback hell." Promises provide a cleaner, more rea
    7 min read
  • What is Callback Hell and How to Avoid it in NodeJS?
    In NodeJS, asynchronous programming can lead to Callback Hell, where deeply nested callbacks make the code hard to read and maintain. This happens when multiple asynchronous operations are chained together, creating a complex structure that's difficult to manage. Callback Hell in NodeJSCallback Hell
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences