Stock Overflow -
I'm trying to process an image collection (~2000 images) with NodeJS. I'm able to extract the information needed, but I'm having a hard time getting the timing right so that I can save the outcome to a JSON file.
Towards the end you'll see
console.log(palette);
// Push single image data to output array.
output.push(palette);
The console.log works fine, but the the push method is appears to be executed after the empty output array has been written to data.json. Tried having a nested promise where I wouldn't write the file until all images have been processed.
The callback function in getPixels gets executed asynchronously.
The order of the output array is arbitrary.
Any and all help greatly appreciated! Thank you!
// Extract color information from all images in imageDirectory
var convert   = require('color-convert'),
    fs        = require('fs'),
    getPixels = require("get-pixels"),
    startTime = Date.now();
var processedImages = new Promise((resolve, reject) => {
  var imageDirectory = 'input',
      images         = fs.readdirSync(imageDirectory),
      output         = [];
  console.log('Found ' + images.length + ' images.');
  for (var image in images) {
    var imageLoaded = new Promise((resolve, reject) => {
      getPixels(imageDirectory + '/' + images[image], function(error, pixels) {
        if(error) {
          return 'Bad image path';
        }
        resolve(pixels);
      });
    });
    imageLoaded.then((pixels) => {
      var palette = {
        coloredPixels  : 0,
        hues           : [],
        image          : images[image],
        classification : false,
        pixelCount     : null
      };
      palette.pixelCount = pixels.shape[0] *
                           pixels.shape[1] *
                           pixels.shape[2];
      for (var i = 0; i < 256; i++) {
        palette.hues[i] = 0;
      }
      for (var i = 0; i < palette.pixelCount; i += 4) {
        var rgb        = [pixels.data[i    ],
                          pixels.data[i + 1],
                          pixels.data[i + 2]],
            hsl        = convert.rgb.hsl(rgb),
            hue        = hsl[0],
            saturation = hsl[1];
        if (saturation) {
          palette.hues[hue]++;
          palette.coloredPixels++;
        }
      }
      console.log(palette);
      // Push single image data to output array.
      output.push(palette);
    });
  }
  resolve(output);
});
processedImages.then((output) => {
  // write output array to data.json
  var json = JSON.stringify(output, null, 2); 
  fs.writeFileSync('data.json', json);
  // Calculate time spent
  var endTime = Date.now();
  console.log('Finished in ' + (endTime - startTime) / 1000 + ' seconds.');
});