How to get directory size in node.js without recursively going through directory?

user772401 picture user772401 · May 26, 2015 · Viewed 8.2k times · Source

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

E.g.

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

Will return me an object like this,

{ 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 size property is not the size of the directory and it's children (aka the sum of the files inside of it).

Is there no way to get the size of a dir (w/the sizes of the files inside of it included) without recursively finding the sizes of the children (and then summing those up)?

I'm basically trying to do the equivalent of du -ksh my-directory but if the given directory is really large (e.g /) than it takes forever to recursively get the true dir size..

Answer

rels picture rels · Apr 5, 2018

You can either spawn a du command on your target directory but as you said it can be rather slow the first time. What you might not know is that du results 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 took initially 8s and then only 0.4s

Hence if your directories are not changing too often, just going with du might be the easiest way to go.

Another solution is to store that in a cache layer, so you can watch your root directory for changes, then compute the size of the folder, store it in a cache and just serve it when needed. To perform this you could use the watch functionality of NodeJS but you'll have some cross platform issues, hence a library like chokidar might be helpful.