Harkirat Saluja Harkirat Saluja - 5 months ago 9
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

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?


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.