Harkirat Saluja Harkirat Saluja - 6 months ago 14
Node.js Question

How to sort array in nodejs based on file size?

I have an array with names of files as the entities of the array. I wanted to sort this array based on the size of the files.

For example,

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


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

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

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

Answer

Try this:

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

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

I assume that these files are in your current directory.