Published on

Building a CLI application with Node.js - 1

Authors
  • avatar
    Name
    mrgenco
    Twitter

While ago, i need an automation for deploying my static files to my Apache Web server. I created my own script with Node.js which basically copies all the files recursively from a given source directory to a given destination.

My requirements were :

  • Get destination and source directories from command line.
  • Create a backup folder of all files in the destination with current date.
  • Copy all the files from source to destination by protecting file hierarchy

It is a very simple command-line application with file operations but it is useful.

Here is the source code with detailed comments.

const fs = require('fs')
const path = require('path')
const prompt = require('prompt-sync')({ sigint: true })

// Get source and destination directory from user
const moveFrom = prompt('Enter a source directory : ')
const moveTo = prompt('Enter a destination directory : ')

copyFiles(moveFrom, moveTo)

async function copyFiles(moveFrom, moveTo) {
  try {
    // Get the files as an array
    const files = await fs.promises.readdir(moveFrom)

    // Loop them all
    for (const file of files) {
      // Get the full paths
      const fromPath = path.join(moveFrom, file)
      const toPath = path.join(moveTo, file)
      // Stat the file to see if we have a file or dir
      const stat = await fs.promises.stat(fromPath)

      if (stat.isFile()) {
        // Now move file async
        await fs.promises.copyFile(fromPath, toPath)
      } else if (stat.isDirectory()) {
        var newTarget = moveTo + '/' + path.basename(fromPath)
        // create a new directory with the same name in the target folder
        await fs.promises.mkdir(newTarget)
        // copy files recursively
        await copyFiles(fromPath, newTarget)
      }
      console.log("Moved '%s' successfully", path.basename(fromPath))
    }
  } catch (e) {
    console.error('An Error occured!', e)
  }
}

For now we dont have backup funcionality but i will be updating the post when i add.

You can find the project on my github page.

Thanks