0

I am trying to run the following code but everytime I run it, I am getting that the markerObj array is empty.

var express = require('express');
var router = express.Router();
var ExifImage = require('exif').ExifImage;
var fs = require('fs');
var path = require('path');

function decimalDegrees(gps, fileName) {
  latitude = gps['GPSLatitude'];
  longitude = gps['GPSLongitude'];
  imageLink = "http://localhost:3000/tmp/" + fileName;
  latitude = latitude[0] + latitude[1] / 60 + latitude[2] / 3600;
  longitude = longitude[0] + longitude[1] / 60 + longitude[2] / 3600;
  console.log(latitude);
  console.log(longitude);
  var markerObject = {
    latitude: latitude,
    longitude: longitude,
    imageLink: imageLink
  };
  return markerObject;
}

router.get('/', function(req, res, next) {

  res.sendFile('map.html', {
    root: 'C:\\Users\\Pranav\\WebstormProjects\\majorProject\\views\\'
  });

});

router.get('/map', function(req, res, next) {
  var markerObj = [];
  fs.readdir("C:\\Users\\Pranav\\WebstormProjects\\majorProject\\tmp", function(err, files) {
    if (err) {
      console.error("Could not list the directory.", err);
      process.exit(1);
    }
    files.forEach(function(file, index) {
      new ExifImage({
        image: path.join("C:\\Users\\Pranav\\WebstormProjects\\majorProject\\tmp", file)
      }, function(error, exifData) {
        if (error)
          console.log('Error: ' + error.message);
        pothole = decimalDegrees(exifData["gps"], file);
        markerObj.push(pothole); // Do something with your data!
      });
    });
    console.log(markerObj);
    res.render('map', {
      markers: markerObj
    });
  });
});

Any idea what is going wrong?

Pranav Jituri
  • 823
  • 1
  • 11
  • 25
  • Could it be that new ExifImage(...) executes the callback asynchronously? it that case, console.log(markerObj) will execute before any of the new ExifImage callbacks executed, you should await these callbacks before printing the array. – areller Apr 20 '17 at 15:10
  • @Arik - I have modified my code a bit. It is still not working. Any idea what is happening? http://pasted.co/9c1e6cce – Pranav Jituri Apr 20 '17 at 15:34
  • @PranavJituri the `callback` in the `fs.readdir` function is Asynchronous. so I would suggest to use a promise. – Shimon Brandsdorfer Apr 20 '17 at 17:27

0 Answers0