使用 files.foreach 从 express 渲染时如何排除文件夹中的某些文件

how to exclude certain files in folder when rendering from express using files.foreach

我的 index.js 文件中有以下代码用于 express/node 应用程序

// BACKGROUNDS
fs.readdir('public/img/backgrounds/',function(err,files){
  if(err) throw err;
  files.forEach(function(file){
    myBGfiles.push(file);
  });
});

它会提取该文件夹中的所有文件,包括 gitignore 和 ds_store。有没有办法在执行此操作时忽略这些文件?

我尝试使用 if 语句来排除它们,但我不确定这是否是完成此操作的最佳方法,也不确定所需的语法。

如有任何帮助,我们将不胜感激。

您将不得不使用 if 语句。 array.forEach(); 方法无法在迭代中停止 See the docs.

因此您要么需要使用 if 语句忽略要忽略的文件,要么需要使用另一种循环,您也可以 continue 使用 if 语句。差别差不多就是这个(注意检查 isBackgroundFileisNonBackgroundFile:

的区别

请注意,我冒昧地做了一些代码格式化。

使用 array.forEach();:

fs.readdir('public/img/backgrounds/', function(err, files) {
    if(err) {
        throw err;
    }

    files.forEach(function(file) {
        if (isBackgroundFile(file)) {
            myBGfiles.push(file);   
        }
    });
});

或使用 ECMAscript 6 for .. of ..

fs.readdir('public/img/backgrounds/', function(err, files) {
    if(err) {
        throw err;
    }

    for (let file of files) {
        if (isNonBackgroundFile(file))   {
            continue;
        }

        myBGfiles.push(file);
    }
});

如果您的 Node 版本不支持 ECMAscript 6,您可以使用 for .. in ..

fs.readdir('public/img/backgrounds/', function(err, files) {
    if(err) {
        throw err;
    }

    for (var file in files) {
        if (files.hasOwnProperty(file)) {
            if (isNonBackgroundFile(file))   {
                continue;
            }

            myBGfiles.push(file);
        }
    }
});

对于 isBackgroundFile 和 isNonBackgroundFile` 你可以这样做:

var path = require('path');

function isBackgroundFile(file) {
    // check file extension or something.
    if(path.extname(file) === ".png" || path.extname(file) === ".jpg") {
        return true;
    }
    return false;
}

function isNonBackgroundFile(file) {
    return !isBackgroundFile(file);
}

如果您想知道是否可以将 fs.readdir 的选项添加到仅 return 具有特定扩展名的文件,那是不可能的。

有一个库可以做到这一点,glob 但我想说 if 语句替代方案完全可以满足您的需求。