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..
To get the size of a file in Node. js, you can use the stat() method provided by the built-in fs module. This method works asynchronously and lists the statistics of a file at the given path. The size of the file is returned in bytes.
Go to Windows Explorer and right-click on the file, folder or drive that you're investigating. From the menu that appears, go to Properties. This will show you the total file/drive size.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With