node. js gets the sum of all the file sizes in the directory

Source: Internet
Author: User

/**
* Gets the sum of all the file sizes in the specified directory in bytes
* @param dir
* @param callback
*/
function Getdirsize (dir,callback) {
var size = 0;
Fs.stat (Dir,function (err,stats) {
if (ERR) return callback (ERR);//If an error occurs
if (Stats.isfile ()) return callback (null,stats.size);//If the file

Fs.readdir (Dir,function (err,files) {//If it is a directory
if (ERR) return callback (ERR);//If traversing directory error
if (files.length==0) return callback (null,0);//If the directory is empty

var count = files.length;//Sentinel variable
for (var i = 0;i<files.length;i++) {
Getdirsize (Path.join (dir,files[i]), function (err,_size) {
if (ERR) return callback (ERR);
Size+=_size;
if (--count<=0) {//If all files (or directories) in the directory are traversed complete
Callback (Null,size);
}
});
}
});
});
}

var walk = function (dir, done) {
var results = [];
var size = 0;
Fs.readdir (dir, function (err, list) {
if (err) return done (ERR);
var pending = List.length;
if (!pending) return done (null, size);
List.foreach (function (file) {
File = Path.resolve (dir, file);
Fs.stat (file, function (err, stat) {
if (stat && stat.isdirectory ()) {
Walk (file, function (err, res) {
size = Size+res;
if (!--pending) Done (null, size);
});
} else {
size = Size+stat.size;
if (!--pending) Done (null, size);
}
});
});
});
};

node. js gets the sum of all the file sizes in the directory

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.