Open In App

Node.js fs-extra move() Function

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.

Syntax:



fs.move(src,dest,options,callback);

Parameters: This function accepts four parameters as mentioned above and described below.

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. 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.

  5. To run the file write the following command in the terminal:

    node index.js

The project structure will look like this:

Example 1:




// Requiring module
import fs from "fs-extra";
  
// Source file
const src = "file.txt";
  
// Destination path
const dest = "destination/file.txt";
  
// Function call
// Using call back function
fs.move(src, dest, (err) => {
  if (err) return console.log(err);
  console.log(`File successfully moved!!`);
});

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:





// Requiring module
import fs from "fs-extra";
  
// Source file
const src = "file.txt";
  
// Destination path
const dest = "destination/file.txt";
  
// Function call
// Using promises
// Setting overwrite to true
fs.move(src, dest, { overwrite: true })
  .then(() => console.log("File moved to the destination"+
                          " folder successfully"))
  .catch((e) => console.log(e));

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.

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


Article Tags :