baniol
11/1/2015 - 10:49 PM

Get largest file from a folder with Promise. node.js

Get largest file from a folder with Promise. node.js

var fs = require('fs');
var path = require('path');

var dir = path.join(__dirname, './');

// var dir = '/Users/marcinbaniowski/Downloads';

var readPromise = new Promise((resolve, reject) => {
  fs.readdir(dir, (err, files) => {
    resolve(files);
  });
})
.then(files => {
  var counter = files.length;
  var stats = [];

  var promises = files.map(file => {
    return new Promise((resolve, reject) => {
      fs.stat(path.join(dir, file), (err, stat) => {
        resolve(stat);
      });
    });
  });
  return {promises: promises, files: files};
})
.then(res => {
  return Promise.all(res.promises).then(stats => {
    return [stats, res.files];
  });
})
.then(res => {
  var stats = res[0];
  var files = res[1];
  var largest = stats
    .filter(stat => stat.isFile())
    .reduce(function (prev, next) {
      if (prev.size > next.size) return prev
      return next
    })
  var retFile = files[stats.indexOf(largest)];
  console.log(retFile + ' : ' + largest.size/1024);
})
.catch(err => console.log('Error: ' + err));