11import path from 'path' ;
2- import { readdirSync , readFileSync , existsSync } from 'fs' ;
2+ import { readdirSync , readFileSync , writeFileSync , existsSync } from 'fs' ;
33import '../utils/marked.min.js' ;
4+ import { computeHash } from '../utils/utils.js' ;
45
56export default ( fastify , options , done ) => {
67 // 添加 / 接口
78 fastify . get ( '/' , async ( request , reply ) => {
89 let readmePath = null ;
10+ const indexHtmlPath = path . join ( options . rootDir , 'public/index.html' ) ;
11+ // console.log(`indexHtmlPath:${indexHtmlPath}`);
912 const files = readdirSync ( options . rootDir ) ;
1013 // console.log(files);
1114 for ( const file of files ) {
@@ -16,20 +19,20 @@ export default (fastify, options, done) => {
1619 }
1720
1821 // 如果未找到 README.md 文件
19- if ( ! readmePath ) {
22+ if ( ! readmePath && ! process . env . VERCEL ) {
2023 let fileHtml = files . map ( file => `<li>${ file } </li>` ) . join ( '' ) ;
21- reply . code ( 404 ) . type ( 'text/html;charset=utf-8' ) . send ( `<h1>README.md not found</h1><ul>${ fileHtml } </ul>` ) ;
22- return ;
24+ return reply . code ( 404 ) . type ( 'text/html;charset=utf-8' ) . send ( `<h1>README.md not found</h1><ul>${ fileHtml } </ul>` ) ;
25+ } else if ( ! readmePath && process . env . VERCEL ) {
26+ const tmpIndexHtml = readFileSync ( indexHtmlPath , 'utf-8' ) ;
27+ return reply . type ( 'text/html;charset=utf-8' ) . send ( tmpIndexHtml ) ;
2328 }
2429
2530 // 读取 README.md 文件内容
2631 const markdownContent = readFileSync ( readmePath , 'utf-8' ) ;
2732
2833 // 将 Markdown 转换为 HTML
2934 const htmlContent = marked . parse ( markdownContent ) ;
30-
31- // 返回 HTML 内容
32- reply . type ( 'text/html' ) . send ( `
35+ const indexHtml = `
3336 <!DOCTYPE html>
3437 <html lang="en">
3538 <head>
@@ -41,7 +44,22 @@ export default (fastify, options, done) => {
4144 ${ htmlContent }
4245 </body>
4346 </html>
44- ` ) ;
47+ ` ;
48+ const indexHtmlHash = computeHash ( indexHtml ) ;
49+ if ( ! existsSync ( indexHtmlPath ) ) {
50+ console . log ( `将readme.md 本地文件:${ indexHtmlPath } ` ) ;
51+ writeFileSync ( indexHtmlPath , indexHtml , 'utf8' ) ;
52+ } else {
53+ const tmpIndexHtml = readFileSync ( indexHtmlPath , 'utf-8' ) ;
54+ const tmpIndexHtmlHash = computeHash ( tmpIndexHtml ) ;
55+ if ( indexHtmlHash !== tmpIndexHtmlHash ) {
56+ console . log ( `readme.md发生了改变,更新本地文件:${ indexHtmlPath } ` ) ;
57+ writeFileSync ( indexHtmlPath , indexHtml , 'utf8' ) ;
58+ }
59+ }
60+
61+ // 返回 HTML 内容
62+ reply . type ( 'text/html;charset=utf-8' ) . send ( indexHtml ) ;
4563 } ) ;
4664
4765 // 新增 /favicon.ico 路由
0 commit comments