Introduction to ensureFileSync() in NodeJS

This method is used to ensure that a file exists at the given location by using a sync process. The response will only be given after the processing is completed. 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.




  • file – This is a string paramter which will hold the location of the file that needs to be ensured.


  • 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 syncEnsureFile.js and copy-paste the following code snippet into that file.

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

node syncEnsureFile.js

Code Snippet

const fs = require('fs-extra')

const file = '/tmp/node/file2.txt'
// file is created along with required directories
console.log("Ensure File Sync Success !")


C:\Users\tutorialsPoint\> node syncEnsureFile.js
Ensure File Sync Success !