Reputation: 11406
In the below code, I iterate through the all the directories and any file with extension 'js' i add it to "files_" array. what I want to do as well is, to create an object or a method "accumulateData" that will be update every time "files_.push" is called. so that, for every iteration, that "files_.push" is called, "accumulateData" will contain the recent/updated contants of "files_.push" and the totalsize.
Moreover, I want the below method to return "accumulateData", so that after the method "getFiles" finish iterations i can call something like,
console.log(accumulateData.totalSize)
please let me know how to achieve that
code:
function getFiles(dir, files_) {
files_ = files_ || [];
var files = fs.readdirSync(dir);
for (var i in files) {
var name = dir + '/' + files[i];
if (fs.statSync(name).isDirectory()) {
getFiles(name, files_);
} else if (name.endsWith('js')) {
//totalSize += fs.statSync(name).size;
files_.push({ name: name, size: fs.statSync(name).size });
/*accumulateData(files, totalSize)
{
files = files;
totoalSize = totalSize;
}*/
}
}
return files_;
//return accumulateData
}
my attempts
let totalSize = 0;
let accumulatedData;
function getFiles(dir, files_) {
files_ = files_ || [];
const files = fs.readdirSync(dir);
for (const i in files) {
const name = dir + '/' + files[i];
if (fs.statSync(name).isDirectory()) {
getFiles(name, files_);
} else if (name.endsWith('js')) {
// files_.push(name);
totalSize += fs.statSync(name).size;
files_.push({ name: name, size: fs.statSync(name).size });
// data(files, totalSize);
accumulatedData = {
files: files,
totalSize: totalSize
};
}
}
return accumulatedData;
}
console.log(getFiles('/home/bakria/Projects/smartvehicle').totalSize);
Upvotes: 3
Views: 42
Reputation: 31712
You can use an object that contain both the array of files and the total size:
function getFiles(dir, obj) {
obj = obj || { files: [], totalSize: 0 }; // if no object is provided then initialize obj with an object that contains an empty array for files and 0 for totalSize
var files = fs.readdirSync(dir);
for(var i = 0; i < files.length; i++) {
var name = dir + '/' + files[i];
var stat = fs.statSync(name); // to minimize the calls to fs.statSync
if (stat.isDirectory()) {
getFiles(name, obj); // pass obj to getFile (recursion)
} else if (name.endsWith('js')) {
obj.totalSize += stat.size; // add this file's size to obj.totalSize
obj.files.push({ name: name, size: stat.size }); // push this file's object into obj.files
}
}
return obj; // return obj
}
The return will be like this:
var result = getFiles("some/dir");
where result
is:
{
files: [/* an array of files */],
totalSize: /* total size of the files */
}
thus result.files
will be the array of files, and result.totalSize
will be the total size.
Upvotes: 2