# Introduction to ensureFileSync() in NodeJS

Node.jsServer Side ProgrammingProgramming

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.

## Syntax

ensureFileSync(file)

## Parameters

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

## Example

• 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
fs.ensureFileSync(file)
console.log("Ensure File Sync Success !")

## Output

C:\Users\tutorialsPoint\> node syncEnsureFile.js
Ensure File Sync Success !
Published on 27-Apr-2021 11:08:44

Advertisements