Author -  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!");
    }
});

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY