Move and rename files to a new directory via Node.js

Inspired by Ali on http://stackoverflow.com/questions/2727167/getting-all-filenames-in-a-directory-with-node-js.

This is to decrease file names like 1.jpg, 2.jpg to 0.jpg, 1.jpg ...

var fs = require('fs');

function walk(currentDirPath, callback) {
  var path = require('path');
  fs.readdir(currentDirPath, function (err, files) {
    if (err) {
       throw new Error(err);
    }
    files.forEach(function (name) {
      var filePath = path.join(currentDirPath, name);
      var stat = fs.statSync(filePath);
      if (stat.isFile()) {
        callback(filePath, stat);
      } else if (stat.isDirectory()) {
        walk(filePath, callback);
      }
    });
  });
}

const sourceDir = '/your/source/files';
walk(sourceDir, function(filePath, stat) {
  const lastSlashIndex = filePath.lastIndexOf('/')
  const dotIndex = filePath.indexOf('.')
  const num = filePath.slice(lastSlashIndex + 1, dotIndex)
  const newPath = filePath.slice(0, lastSlashIndex) + '/new/' + (num-1) + '.jpg'
  fs.rename(filePath, newPath, (err) => {
    if (err) throw err;
    console.log('renamed complete');
  });
});