Harkirat Saluja Harkirat Saluja - 1 year ago 144
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download