简体   繁体   English

如何在排除某些具有 glob 模式的路径的情况下在 nodejs 中获取文件夹大小?

[英]How to get a folder size in nodejs with excluding certain paths with glob pattern?

I want to calculate the total archive file size before archiving to show a progress bar.我想在存档之前计算总存档文件大小以显示进度条。 I have some folder which are exluded from zipping with are defined with a glob pattern.我有一些从压缩中排除的文件夹是用 glob 模式定义的。 How can you get a folder size with a glob filter?如何使用全局过滤器获取文件夹大小?

It appears you can't use regular expressions;看来您不能使用正则表达式; you can use https://www.npmjs.com/package/glob and loop through the files that match your glob pattern, and get the size of each.您可以使用https://www.npmjs.com/package/glob并遍历与您的 glob 模式匹配的文件,并获取每个文件的大小。 Something roughly like (i haven't tested this code):大致类似于(我还没有测试过这段代码):

const fs = require('fs')
const glob = require('glob')

let totalSize = 0 // bytes
 
// options is optional
glob("**/*.js", options, function (er, files) {
  files.forEach(f => {
    totalSize += fs.statSync(f)
  })
})

With the help of above answer this is the solution在上述答案的帮助下,这是解决方案

const glob = require('glob');
const fs = require('fs');

function getFolderSizeByGlob(folder, { ignorePattern: array }) {
    const filePaths = glob.sync('**', { // "**" means you search on the whole folder
        cwd: folder, // folder path 
        ignore: array, // array of glob pattern strings
        absolute: true, // you have to set glob to return absolute path not only file names
    });
    let totalSize = 0;
    filePaths.forEach((file) => {
        console.log('file', file);
        const stat = fs.statSync(file);
        totalSize += stat.size;
    });
    return totalSize;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM