ensureFile() function in fs-extra - NodeJS

Node.jsServer Side ProgrammingProgramming

Introduction to Async ensureFile()

This method is used to ensure that a file exists at the given location. If the files that is ensured to be created is not present or the respective directories are not present, these directories and files are created. If the file already exists, it is not modified or no change is made.


ensureFile(file, [, callback])


  • file – String parameter which will contain name of the file and its location that needs to be ensured.

  • callback – This function will give a callback if any error occurs.

Example 1

  • Check that fs-extra is installed before proceeding; if not, install fs-exra.

  • You can use the following command to check whether fs-extra is installed or not.

npm ls fs-extra
  • Create a ensureFile.js and copy-paste the following code snippet into that file.

  • Now, run the following command to run the following code snippet.

node asyncEnsureFile.js

Code Snippet

const fs = require('fs-extra')

const file = '/tmp/node/file.txt'

// Ensuring File with a callback:
fs.ensureFile(file, err => {
   // Error will be null in case of success
   console.log(err) // => null/undefined
   // File is create

// Ensuring file with Promises:
.then(() => {
   console.log('Async Success with Promises!')
.catch(err => {

// Ensuring file with async/await:
async function ensureFileExample (f) {
   try {
      await fs.ensureFile(f)
      console.log('Await Success!')
   } catch (err) {


C:\Users\tutorialsPoint\> node asyncEmptyDir.js
Async Success with Promises!
Await Success!
Updated on 27-Apr-2021 11:07:21