0

This code is supposed to save the most recently uploaded file to the lastdownloadedimage variable but I am getting an error. How can this be fixed to work as intended?

Error:

UnhandledPromiseRejectionWarning: ReferenceError: lastdownloadedimage is not defined

Code:

var path = require("path");
var fs = require("fs");
var recent;
var getMostRecent = function (dir, cb) {
  var dir = path.resolve(dir);
  var files = fs.readdir(dir, function (err, files) {
    var sorted = files
      .map(function (v) {
        var filepath = path.resolve(dir, v);
        return {
          name: v,
          time: fs.statSync(filepath).mtime.getTime(),
        };
      })
      .sort(function (a, b) {
        return b.time - a.time;
      })
      .map(function (v) {
        return v.name;
      });

    if (sorted.length > 0) {
      cb(null, sorted[0]);
    } else {
      cb("Y U NO have files in this dir?");
    }
  });
};

getMostRecent(downloadanduploadPath, function (err, recent) {
  if (err) console.error(err);
  console.log(recent);
  return recent;
});
var lastdownloadedimage = recent;

console.log(lastdownloadedimage + "1hi");
Matt Oestreich
  • 8,219
  • 3
  • 16
  • 41
Roboman Robo
  • 599
  • 2
  • 5
  • 16
  • lastdownloadedimage is defined, the error should read downloadanduploadPath is not defined – Lawrence Cherone Aug 06 '20 at 21:17
  • `recent` altered inside your callback, not in your main scope – tarkh Aug 06 '20 at 21:17
  • Using `let` and `const` instead of using `var` everywhere also helps mitigate scoping issues (which this appears to be).. For example, `var path = require('path')` and `var fs = require('fs')` should be `const` and `var recent` should be `let recent`. This is because you do not plan on reassigning the variable name `path` or `fs` so they should be constants. However, you do plan on reassigning `recent`, therefore `let` should be used. Granted there are "edge cases", but thinking in terms of "do I plan on reassigning this variable?" is a great rule of thumb. U can push items to a const arr tho. – Matt Oestreich Aug 06 '20 at 21:34

0 Answers0