Search code examples
node.jswebpackhtml-webpack-plugin

Analog `fs.readdirSync` node.js without recursive


I try get only html files to my folder. But my code get all folders into my root folders and return result me. I want to get only .html files.

My structure project

src folder folder2 index.html inner.html

I need to only index.html and inner.html My code:

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

Please, help me send only .html files into my function


Solution

  • You need filter your files before 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');