Skip to content
Related Articles

Related Articles

Improve Article
NodeJS fs-extra ensureFileSync() function
  • Last Updated : 02 Mar, 2021

The ensureFileSync() function is the synchronous version of ensureFile() function. The function makes sure that the file exists, if the files do not exist it will be created by the function. If the requested file is in a directory that does not exist, the directory and the file inside it will be created by the function itself. If the file exists already, it is not modified. createFileSync() function can also be used in place of ensureFileSync() function and the result will be same.

Syntax:

fs.ensureFileSync(file)

or

fs.createFileSync(file)

Parameters:

  • file: It is a string that contains the file path.

Return value: It does not return anything.



Follow the steps to implement the function:

  1. The module can be installed by using the following command:
    npm install fs-extra
  2. After the installation of the module you can check the version of the installed module by using this command:

    npm ls fs-extra

  3. Create a file with the name index.js and require the fs-extra module in the file using the following command:

    const fs = require('fs-extra');
  4. To run the file write the following command in the terminal:

    node index.js

Project Structure: The project structure will look like this.

Example 1:

index.js






// Requiring module
const fs = require("fs-extra");
  
// Function to check
// if file exists
// or not
const fileExists = (file) => {
  if (fs.existsSync(file)) {
    return "File exists";
  } else {
    return "File do not exist";
  }
};
  
// This file already
// exist so function
// will not do anything
const file = "file.txt";
  
// Checking before
// calling function
const before = fileExists(file);
console.log(`Before function call ${before}`);
  
// Function call
fs.ensureFileSync(file);
  
// Checking after calling function
const after = fileExists(file);
console.log(`After function call ${after}`);

Output:

Example 2:

index.js




// Requiring module
const fs = require("fs-extra");
  
// Function to check
// if file exists
// or not
const fileExists = (file) => {
  if (fs.existsSync(file)) {
    return "File exists";
  } else {
    return "File do not exist";
  }
};
  
// This file and directory
// do not exist so both
// will be created
const file = "dir/file.txt";
  
// Checking before
// calling function
const before = fileExists(file);
console.log(`Before function call ${before}`);
  
// Function call
fs.ensureFileSync(file);
  
// Checking after calling function
const after = fileExists(file);
console.log(`After function call ${after}`);

Output:

Reference: https://github.com/jprichardson/node-fs-extra/blob/HEAD/docs/ensureFile-sync.md




My Personal Notes arrow_drop_up
Recommended Articles
Page :