Search code examples
javascriptnode.jsenoent

ENOENT: Node.js script, fs.rename, to divide and move files from 1 folder to multiple other folders


I am stuck with my script. My goal is: I have a folder of images and want to divide and move them to multiple other folders (which are always there). The folder limit is 200 files and in my loop, after the first folder is succesfully filled with 200 files, at the 2nd file of the 2nd folder I get always the error:

    Error: ENOENT: no such file or directory, rename '/home/.../chunkDirsMoveFiles/input/resize/20150818_051550_web.jpg' -> './output/dir_2/20150818_051550_web.jpg'] {
  errno: -2,
  code: 'ENOENT',
  syscall: 'rename',
  path: '/home/.../chunkDirsMoveFiles/input/resize/20150818_051550_web.jpg',
  dest: './output/dir_2/20150818_051550_web.jpg'
}

My code for that (I guess the problem start generally at currentdir = 1):

const { clear } = require("console");
const fs = require("fs")
const path = require("path")
// const { fileSystemHelper } = require('../allhelpers/fileSystemHelper.js')

const dirLimit = 200

clear()

// Fn to get all file paths of the input folder
const getAllFiles = function(dirPath, arrayOfFiles) {
  files = fs.readdirSync(dirPath)

  arrayOfFiles = arrayOfFiles || []

  files.forEach(function(file) {
    if (fs.statSync(dirPath + "/" + file).isDirectory()) {
      arrayOfFiles = getAllFiles(dirPath + "/" + file, arrayOfFiles)
    } else {
      arrayOfFiles.push(path.join(__dirname, dirPath, "/", file))
    }
  })
  
  return arrayOfFiles
}

const images = getAllFiles("input/resize")

const dirAmount = Math.round(images.length/dirLimit)

for (let i = 0; i < dirAmount; i++) {
  fs.mkdir(`./output/dir_${i + 1}`, function(err) {
    // if (err) {
    //   console.log(err)
    // } else {
    //   console.log("New directory successfully created.")
    // }
  })
}

currentDir = 1

for (let i = 0; i < dirAmount; i++) {

  for (let k = 0; k < dirLimit; k++) {

    const theFilePath = images[k].split('/')
    const newPath = theFilePath[(theFilePath.length)-1]

    fs.rename(images[k],  `./output/dir_${currentDir}/${newPath}`, function (err) {
      if (err) throw err
      console.log('Successfully renamed/moved!')
    })

  }
  currentDir += 1
}

Solution

  • Look at the loops: for each directory, you take at most < dirLimit files and move them all to that directory (so 200 first files). Then, for the next directory, the loop does the same: takes 200 files from the start of the array... but hey! The files were already moved to the previous directory in the previous iteration.

    The loop doesn't use i, and it doesn't advance through the list of files.