The move() function moves a file or a directory from source to the destination specified by the user. If you want to move a file to a folder in which a file with the same name already exists, the function will overwrite the file if we have set the option of overwrite to true else it will throw an error that a file already exists in the folder.
Parameters: This function accepts four parameters as mentioned above and described below.
- src: It is a string that contains the path of the file which is to be moved (source path).
- dest: It is a string that contains the path where the file will be moved (destination path).
- options: It is an object with property overwrite which can be true or false. By default, : false. If it is set to true the file will be overwritten if a file with the same name exists in the destination folder.
- callback: It is a function that will be called when the move() function has been performed. It will either result in an error or success. It is an optional parameter, we can use promises in place of callback function as well.
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');
Create an empty folder with the name destination and a file with the name file.txt. We will be moving the file into the destination folder using this function.
To run the file write the following command in the terminal:
The project structure will look like this:
Output: Now check the destination folder we created earlier. You will find that the file with the name file.txt is now moved to the destination folder
Example 2: Let’s take another example. In the destination folder create a file with the name file.txt and create another file with the name file.txt outside the destination folder. We are going to try the overwrite property of the function in this example. The folder structure now looks like:
Output: You will observe that the file in the destination folder is now overwritten by the file outside the folder.
Note: If you have not set the overwrite property to false the above program will result in the following error:
So this is how we can use move() function in our program.