UNPKG

chasejia_js-vitepress

Version:

js -> markdown-> vitepress

48 lines (46 loc) 2.23 kB
import path, { resolve } from 'node:path'; import fs from 'node:fs'; const DIR_PATH = resolve(__dirname, '../') // 获取到当前项目的根目录 const WHITE_LIST = ['index.md', '.vitepress', 'public'] // 白名单,不处理对应的目标文件 const isDirectory = (path) => fs.lstatSync(path).isDirectory() // 判断是否是文件夹 const intersections = (arr1, arr2) => Array.from(new Set(arr1.filter((item) => !new Set(arr2).has(item)))) // 将文件进行过滤(Array.from浅拷贝) export const set_sidebar = (pathname) => { const dirPath = resolve(DIR_PATH, pathname) // 获取pathname的路径 // 读取pathname下的所有文件或者文件夹 // 将目标文件或文件夹的名称以数组形式抛出=>[ '基础.md', '进阶.md' ] // readdirSync 读取目录的内容 const files = fs.readdirSync(dirPath) // 将符合白名单的数组进行剔除并将处理后的数组进行返回 const items = intersections(files, WHITE_LIST) return getList(items, dirPath, pathname); } // 如果是文件,那么就不用继续递归 // 如果是文件夹那么就生成一个数组继续递归直到全部遍历完 function getList(params, path, pathname) { const res = [] // 存放结果 for (let file in params) { // 开始遍历params const dir = resolve(path, params[file]) // 拼接目录 const isDir = isDirectory(dir) // 判断是否是文件夹 if (isDir) { const files = fs.readdirSync(dir) // 如果是文件夹,读取之后作为下一次递归参数 res.push({ text: params[file], collapsible: true, items: getList(files, dir, `${pathname}/${params[file]}`), // selected: true // Add selected state }) } else { // 获取名字 const name = params[file].split('.')[0] let a = pathname.split(""); a.shift(); pathname = a.join(""); res.push({ text: name, link: `${pathname}/${name}`, // selected: true // Add selected state }) } } return res }