1

I have the following script which reads in all images from a directory and create a GIF.

async function createGif(algorithm) {
  return new Promise(async resolve1 => {
    const files = await promisify(readdir)(imagesFolder)

    // Bunch of other things
    // Happening here

    // draw an image for each file and add frame to encoder
    for (const file of files) {
      await new Promise(resolve3 => {
        const image = new Image()
        console.log(`reading ${file}`)
        image.onload = () => {
          ctx.drawImage(image, 0, 0)
          encoder.addFrame(ctx)
          resolve3()
        }
        image.src = path.join(imagesFolder, file)
      })
    }
  })
}

The images are of the pattern: image1,image2,image3,...image30.

However, the files are being read in this order when I check the console:

reading screenshot1.png
reading screenshot10.png
reading screenshot11.png
reading screenshot12.png
reading screenshot13.png
reading screenshot14.png
reading screenshot15.png
reading screenshot16.png
reading screenshot17.png
reading screenshot18.png
reading screenshot19.png
reading screenshot2.png
reading screenshot20.png

Why is it skipping from screenshot1 to screenshot10? It should be reading the files in the correct order in which they are in the directory. Like this:

reading screenshot1.png
reading screenshot2.png
reading screenshot3.png
...
reading screenshot10.png

How can I fix this?

Aman
  • 387
  • 8
  • 33
  • 2
    You should drop the line `return new Promise(async resolve1 => {`, it does nothing useful – Bergi Jan 13 '22 at 08:57
  • 3
    Who says that readdir gives you the files in the order you want? You shouldn't be relying on a strict ordering when coming from readdir. If you want them sorted some particular way, then sort them before processing them. – jfriend00 Jan 13 '22 at 08:59
  • 1
    This is how `readdir` returns them. Note they are in the absolutely correct lexicographical order. Or would you expect `file b` to come before `file ab`? – VLAZ Jan 13 '22 at 08:59
  • 1
    "*Why is it skipping from screenshot1 to screenshot10?*" - because that's the normal lexical sort order. "*It should be reading the files in the correct order in which they are in the directory.*" - they *are* in that order in the directory (or, in no order at all). It just might be that whatever file manager you are using does use a natural sort to display its list of files. If you care about the order in which you load them, [sort the array yourself](https://stackoverflow.com/q/2802341/1048572). – Bergi Jan 13 '22 at 08:59
  • 2
    As a good practice, always sort an array if you require exact order for some operation. Never take the order of an array coming from any source for granted. – Ricky Mo Jan 13 '22 at 09:04
  • Just tested it and in windows file are sorted by natural sort. 001,1, 2, 3, 011, 20 – adiga Jan 13 '22 at 09:05

0 Answers0