Skip to content
The Chat Archive
gpt-3.5-turbo-0301· OpenAI WildChat-4.8M (AI2)

nodejs 查找文件下文件名为xxx.entry.js的文件,如果符合则输出该文件名

  1. User

    nodejs 查找文件下文件名为xxx.entry.js的文件,如果符合则输出该文件名

  2. Assistant

    以下是一种可以实现该功能的方式:

    const fs = require('fs');
    const path = require('path');
    
    const folderPath = './folder'; // 文件夹路径
    
    fs.readdir(folderPath, (err, files) => { // 读取文件夹下的所有文件
      if (err) throw err;
    
      files.forEach(file => { // 遍历文件夹下的所有文件
        const extname = path.extname(file); // 获取文件扩展名
    
        if (extname === '.entry.js') { // 判断是否是指定的文件类型
          console.log(file); // 输出文件名
        }
      });
    });
    

    其中,fs.readdir 方法可以读取指定文件夹下的所有文件,其第一个参数为文件夹路径,第二个参数为回调函数,回调函数中的 files 参数即为读取到的文件数组。然后,对文件数组进行遍历,使用 path.extname 方法获取文件扩展名,再与指定的扩展名 .entry.js 进行对比,如果相同则输出该文件名。