How to sort an array in nodejs based on file size?

I have an array with file names as array objects. I wanted to sort this array based on file size.

For example,

var arr=['index.html','README.md','index.html']; 

So what I currently have is that I am creating an object with the name of the files as the key and the file size as the value.

Now I am extracting these files from a remote location, so I can get the file size from the header content-length.

Is there a better way to do this? Will it be possible to do this locally, with which I mean the file size to read and create an object based on this?

+4
source share
4 answers

Try the following:

var arr = ['index.html','README.md','index.html'];

arr.sort(function(a, b) {
  return fs.statSync(a).size - fs.statSync(b).size;
});

, .

+3

memoized promises:

var arr = ['index.html', 'README.md', 'index.html'];
var sortedArray = arr
    // get the size of each file
    .map(file => { return { file: file, size: fs.statSync(file).size } })
    // sort by size ascending
    .sort((a, b) => a.size > b.size)
    // return a simple sorted array of the file names only
    .map(f => f.file);

console.log(sortedArray);
+1

Bluebird, :

var Bluebird = require('bluebird'),
  fs = Bluebird.promisifyAll(require('fs')),
  arr = [
     // your file array
  ];

// retriving size of each file
function getSize(file){
    return fs.statAsync(file).then(stats => stats.size);
}

Promise.all(arr.map( file=> getSize(file).then(size=> {return {file, size}})))
  .then(sizedArry => {
    console.log(sizedArry);
    var sortedArray = sizedArry.sort((a, b) => a.size > b.size); // sorting array based on size
    console.log('sorted array: ', sortedArray);
    // if you want only the sorted file names...
    return sortedArray.map(element => element.file);
  });
0
source

@Gothdo answer extension:

var fs = require('fs');
var arr = ['index.html','README.md','index.html'];

function memoize(func) {
  var cache = {};

  // assumes argument is string
  return function memoized(str) {
    if (cache[str]) return cache[str];

    return (cache[str] = func(str));
  };
}

var statSync = memoize(fs.statSync);

arr.sort(function sort(a, b) {
  return statSync(a).size - statSync(b).size;
});

When writing a function , you should improve the performance of the sorting algorithm, which is quickly sorted in node, the last time I checked.

0
source

Source: https://habr.com/ru/post/1623709/


All Articles