如何在方法中创建和调用要调用的对象

时间:2017-12-04 17:00:55

标签: javascript

在下面的代码中,我遍历所有目录和任何扩展名为“js”的文件,我将其添加到“files_”数组中。 我想要做的是,创建一个对象或方法“accumulateData”,每次调用“files_.push”时都会更新。这样,对于每次迭代,都是如此 调用“files_.push”,“accumulateData”将包含“files_.push”和totalsize的最新/更新内容。

此外,我希望下面的方法返回“accumulateData”,这样在“getFiles”方法完成迭代后,我可以调用类似的东西,

console.log(accumulateData.totalSize)

请让我知道如何实现

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
}

我的尝试

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);

1 个答案:

答案 0 :(得分:2)

您可以使用包含文件数组和总大小的对象:

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
}

回报将是这样的:

var result = getFiles("some/dir");

其中result是:

{
    files: [/* an array of files */],
    totalSize: /* total size of the files */
}

因此result.files将是文件数组,result.totalSize将是总大小。