# 归档自动化——读写文件

强烈谴责版本不符的 Node.js 中文网 API 文档

这一次自动化归档的目的是为 articles 目录下每一个月份目录形成一个归档文件。

归档文件直接以 README.md 命名,包含月份目录下全部文章的链接。

经过试验,可以在 congfig.js 文件中做,并且可以被之前的 autoDir 识别到。

这次主要用到 Node.js 读写文件的 API。

function autoArchieve() {
    const articlePath = './docs/articles'
    const dirs = fs.readdirSync(articlePath, { withFileTypes: true })
 
    for (let dir of dirs) {
        if (dir.isDirectory()) {
            const path = articlePath + '/' + dir.name
            const readme = path + '/README.md'
            let readmeContent = `# ${dir.name}\n\n`

            const relativePath = '/articles/' + dir.name

            const filenameList = fs.readdirSync(articlePath + '/' + dir.name)
            for (let filename of filenameList) {
                if (filename !== 'README.md') {
                    const content = fs.readFileSync(path + '/' + filename, { encoding: 'utf-8' })
                    const firstLine = content.split('\n')[0]
                    const title = firstLine.substr(2, firstLine.length - 3)
                    readmeContent += `### [${title}](${relativePath}/${filename})\n\n`
                }
            }

            fs.writeFileSync(readme, readmeContent, { flag: 'w' })
        }
    }
}

但是,config.js 里的代码似乎不会及时热更新,即使 console 里表现出来的是更新了。

所以,每次修改之后最后都重新 npm run docs:dev 来查看最新的开发结果。

以后有时间再研究研究怎样用插件或者别的方法实现吧~

Last Updated: 7/21/2020, 8:50:24 PM