逐个读取文件夹文件名字

167 阅读1分钟

代码

const { join, extname, basename } = require("path");
const fs = require("fs");
// 获取入口
function getEntries(path) {
  const entries = {};
  // 目录路径
  const dir = join(__dirname, path);
  // 读取这个路径
  fs.readdirSync(dir).forEach((file) => {
    const fullPath = join(dir, file);
    // fs.statSync()方法用于异步返回有关给定文件路径的信息。
    const stat = fs.statSync(fullPath);
    // path.extname() 方法返回 path 的扩展名 .js/.html
    const en = extname(fullPath);
    const bn = basename(file);
    // path.basename() 方法返回 path 的最后一部分
    // 返回: 'quux.html' "quux.js"
    if (stat.isFile() && en === ".js") {
      entries[bn.replace(".js", "")] = fullPath;
    }
  });
  return entries;
}

效果

console.log("getEntries()", getEntries("src"));

console.log

getEntries() { main: 'c:\\Users\\10177\\Desktop\\testfolder\\test\\src\\main.js' }