查找文件夹下的文件
大约 1 分钟约 315 字
import fs from 'fs'
import path from 'path'
// 读取内容目录中的文件列表
function readDir(dir, depth) {
const files = fs.readdirSync(dir) // 读取文件夹中的所有内容
const folderName = path.basename(dir)
const folderItem = {
text: folderName,
prefix: `/${folderName}`,
icon: 'pen-to-square',
depth,
children: []
}
if (depth === 0) {
folderItem.text = '博文'
folderItem.prefix = '/zh' + folderItem.prefix
}
files.forEach(file => {
const filePath = path.join(dir, file) // 获取文件的完整路径
const stat = fs.statSync(filePath) // 判断文件是否是一个文件夹
depth++
if (stat.isDirectory()) {
const item = readDir(filePath)
item.prefix += '/'
item.depth = depth
folderItem.children.push(item) // 递归处理子文件夹 // 如果是一个文件夹,继续递归遍历子文件夹
} else {
// 根据你的要求修改名字
let newName = file.replace(/\d{4}-\d{2}-\d{2}-/g, '')
console.log(['newName', newName])
fs.rename(filePath, `${dir}/${newName}`, err => {
if (err) {
console.log('失败: ', err)
}
})
// 读取文件内容
const fileText = fs.readFileSync(filePath, 'utf8')
let newReplaceContent = ''
let replaceContent = fileText.match(/---[\s\S]*?---/)
if (replaceContent) {
replaceContent = replaceContent[0]
const date = replaceContent.match(/date:\s*(\d{4}-\d{2}-\d{2})/)
let tag = replaceContent.match(/tag:\s*([\s\S]*?)\n/)
let tagContent = `tag:` + '\n'
if (tag) {
tag = (tag[1] || '').split(',')
tag.forEach(v => {
tagContent += ` -` + v
})
}
newReplaceContent = `---
icon: pen-to-square
date: ${date}
category:
- ${folderItem.text}
${tagContent}
---`
}
// 替换文件内容
const newFileText = fileText.replace(/---[\s\S]*?---/, newReplaceContent)
// 写回文件
fs.writeFileSync(filePath, newFileText)
const fileName = file.replace('.md', '')
const fileItem = {
text: fileName,
link: fileName,
depth
}
folderItem.children.push(fileItem)
}
})
return folderItem
}
readDir('./src/posts')