The ensureFile() function makes sure that the file user is requesting exists. If the file doesn’t exist the function will create a new file. Even if the user is requesting a file that is inside some directory, but if the directory does not exist the function will create the directory and the file in that directory itself. If the file already exists it will not be modified. createFile() is the other name of ensureFile() function which means we can use createFile() function in place of ensureFile() and everything will work as it is.
- file: It is a string that contains the file path.
- callback: It will be called after the task is completed by the function. It will either result in an error or success. Promises can also be used in place of the callback function.
Return value: It does not return anything.
Follow the steps to implement the function:
The module can be installed by using the following command:
npm install fs-extra
After the installation of the module you can check the version of the installed module by using this command:
npm ls fs-extra
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');
To run the file write the following command in the terminal:
Project Structure: The project structure will look like this.
Example 1: Create a file with the name file.txt. We will be passing this file in our function
Output: Since we have created the file earlier the function will not create a new file and it will not modify the data our file contains.
Example 2: This time we will be passing the file path which does not exist.
Output: You will observe that now a directory is created with the name dir and it contains a file with the name file.txt.