by Sai gowtham

How to move files in Node.js

In this tutorial, we are going to learn about how to move the files from one directory to another directory in Node.js.

Using the fs.rename method

Node.js has a built-in file system module, which has an fs.rename() method that helps us to asynchronously move a file from one directory to another.

Here is an example:

const fs = require("fs");
const path = require("path");

const currentPath = path.join(__dirname, "public", "car.png");
const destinationPath = path.join(__dirname, "images", "car.png");

fs.rename(currentPath, destinationPath, function (err) {
    if (err) {
        throw err
    } else {
        console.log("Successfully moved the file!");
    }
});

The first argument in the fs.rename() method is currentPath where the file lives in, the second argument is the destinationPath and third argument is the callback function that runs with an err argument.

Note: The fs.rename() doesn’t work correctly on cross partitions or virtual file systems.

To move files correctly across all platforms there is an npm package called mv, which first tries fs.rename() method then fallbacks to piping a source file to the destination folder and deletes the source file.

To use it, first we need to install an mv package from the npm by running the following command.

npm install mv

Usage:

const mv = require('mv');

const currentPath = path.join(__dirname, "public", "car.png");
const destinationPath = path.join(__dirname, "images", "car.png");

mv(currentPath, destinationPath, function(err) {
     if (err) {
        throw err
    } else {
        console.log("Successfully moved the file!");
    }
});

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course