0

此代码应该将最近上传的文件保存到lastdownloadedimage变量中,但出现错误。如何修复它以按预期工作?

错误:

UnhandledPromiseRejectionWarning: ReferenceError: lastdownloadedimage 未定义

代码:

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");
4

0 回答 0