randImg.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. const fs = require('fs');
  2. const path = require('path');
  3. console.log('Current directory:', __dirname);
  4. // _post 文件夹的相对路径
  5. const postsFolder = path.join(__dirname, '..', 'source', '_posts');
  6. fs.readdirSync(postsFolder).forEach(file => {
  7. const filePath = `${postsFolder}/${file}`;
  8. if (file.endsWith('.md')) {
  9. let content = fs.readFileSync(filePath, 'utf8');
  10. // 匹配 metadata 部分
  11. const metadataRegex = /^---\n([\s\S]*?)\n---/;
  12. const match = content.match(metadataRegex);
  13. if (match) {
  14. // 检查是否已经存在 index_img
  15. if (!/\bindex_img\b/.test(content)) {
  16. const metadata = match[1];
  17. const updatedMetadata = metadata.replace(/^\s*date:\s*([\d\s-:]+)$/m, "date: $1\nindex_img: https://api.limour.top/randomImg?d=$1");
  18. // 将更新后的 metadata 放回文件内容
  19. content = content.replace(metadata, updatedMetadata);
  20. // console.log(updatedMetadata);
  21. // console.log(content);
  22. // 将更新后的内容保存回原文件
  23. fs.writeFileSync(filePath, content, 'utf8');
  24. console.log(`File updated: ${filePath}`);
  25. } else {
  26. console.log(`Index_img already exists in file: ${filePath}`);
  27. }
  28. }
  29. }
  30. });
  31. console.log('Script completed.');