代码之家  ›  专栏  ›  技术社区  ›  Aleksandr Gvozdev

模拟'fs。readdirSync`节点。无递归的js

  •  0
  • Aleksandr Gvozdev  · 技术社区  · 6 年前

    我尝试只将html文件获取到我的文件夹中。但我的代码将所有文件夹都放入我的根文件夹并返回结果。我只想得到 .html 文件。

    我的结构项目

    src folder folder2 index.html inner.html

    我只需要 index.html inner.html 我的代码:

    function generateHtmlPlugins(templateDir) {
      const templateFiles = fs.readdirSync(join(rootDir, templateDir));
    
      return templateFiles.map(item => {
        const parts = item.split('.');
        const name = parts[0];
        const extension = parts[1];
    
        return new HtmlWebpackPlugin({
          filename: `${name}.html`,
          template: join(rootDir, `./${templateDir}/${name}.${extension}`),
          inject: false
        });
      });
    }
    
    const htmlPlugins = generateHtmlPlugins('./src');
    

    请帮我只发送 .html 文件到我的函数中

    1 回复  |  直到 6 年前
        1
  •  0
  •   Роман Татаринов    6 年前

    你需要先过滤你的文件 map

    function generateHtmlPlugins(templateDir) {
      const templateFiles = fs.readdirSync(join(rootDir, templateDir));
      const htmlFiles = templateFiles.filter(item => item.split('.')[1] === 'html');
    
      return htmlFiles.map(item => {
        const parts = item.split('.');
        const name = parts[0];
        const extension = parts[1];
    
        return new HtmlWebpackPlugin({
          filename: `${name}.html`,
          template: join(rootDir, `./${templateDir}/${name}.${extension}`),
          inject: false
        });
      });
    }
    
    const htmlPlugins = generateHtmlPlugins('./src');