How do I get the size of a directory in node.js without going through the directory recursively?

How do I get the size of a directory in node.js without recursively traversing all the children in the directory?

eg.

var fs = require('fs');
fs.statSync('path/to/dir');

      

Will return me such an object,

{ dev: 16777220,
  mode: 16877,
  nlink: 6,
  uid: 501,
  gid: 20,
  rdev: 0,
  blksize: 4096,
  ino: 62403939,
  size: 204,
  blocks: 0,
  atime: Mon May 25 2015 20:54:53 GMT-0400 (EDT),
  mtime: Mon May 25 2015 20:09:41 GMT-0400 (EDT),
  ctime: Mon May 25 2015 20:09:41 GMT-0400 (EDT) }

      

But the property size

is not the size of the directory, but its children (for example, the sum of the files inside it).

Isn't there a way to get the size of a directory (with the sizes of the files inside it) without recursively finding the sizes of the children (and then summing them up)?

I'm basically trying to do an equivalent du -ksh my-directory

, but if the given directory is really big (for example /

), then it is forever required to recursively get the true size of dir.

+3


source to share


2 answers


You can either invoke the command du

in your target directory, but as you said it can be quite slow the first time around. You may not be aware that the results du

seem to be cached somehow:

$ time du -sh /var
13G /var
du -sh /var  0.21s user 0.66s system 9% cpu 8.930 total
$ time du -sh /var
13G /var
du -sh /var  0.11s user 0.34s system 98% cpu 0.464 total

      

It first took 8 seconds and then just 0.4 seconds



Hence, if your directories don't change too often, just switching from du

might be the easiest way.

Another solution is to store this in a cache layer, so you can watch the root of the changes, then calculate the size of the folder, store it in the cache, and just serve it up when needed. You can use NodeJS clock functions to accomplish this, but you will have cross platform issues, so a library like chokidar might be helpful.

+1


source


You should try the "getFolderSize" node module https://www.npmjs.com/package/get-folder-size

Using

getFolderSize(folder, [regexIgnorePattern], callback)

      



Example:

var getSize = require('get-folder-size');

getSize(myFolder, function(err, size) {
  if (err) { throw err; }

  console.log(size + ' bytes');
  console.log((size / 1024 / 1024).toFixed(2) + ' Mb');
});

      

-1


source







All Articles