image2local.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { promises as fs } from 'fs';
  2. import { dirname, join } from 'path';
  3. import { fileURLToPath } from 'url';
  4. import { fetch } from 'node-fetch';
  5. const __dirname = dirname(fileURLToPath(import.meta.url));
  6. const markdownDir = join(__dirname, 'src'); // Markdown文件所在目录
  7. const imagesDir = join(__dirname, 'src/images'); // 图片下载目录
  8. // 确保图片下载目录存在
  9. await fs.mkdir(imagesDir, { recursive: true }).catch(console.error);
  10. // 下载图片
  11. async function downloadImage(url, filepath) {
  12. const response = await fetch(url,{
  13. headers: {
  14. 'referer': 'https://ft07.com'
  15. }
  16. });
  17. const buffer = await response.buffer();
  18. await fs.writeFile(filepath, buffer);
  19. console.log('Downloaded: ' + filepath);
  20. }
  21. // 替换Markdown中的图片链接并下载图片
  22. async function replaceImageLinksInFile(filePath) {
  23. let data = await fs.readFile(filePath, 'utf8');
  24. const regex = /!\[.*?\]\((https:\/\/res07\.ftqq\.com\/.*?\.png)\)/g;
  25. let match;
  26. while ((match = regex.exec(data)) !== null) {
  27. const imageUrl = match[1];
  28. const imageName = imageUrl.split('/').pop();
  29. const localImagePath = join(imagesDir, imageName);
  30. // 替换Markdown中的图片链接为本地路径
  31. data = data.replace(imageUrl, localImagePath);
  32. // 下载图片
  33. await downloadImage(imageUrl, localImagePath);
  34. }
  35. // 保存更新后的Markdown文件
  36. await fs.writeFile(filePath, data, 'utf8');
  37. console.log('Updated file: ' + filePath);
  38. }
  39. // 读取并处理每个Markdown文件
  40. const files = await fs.readdir(markdownDir);
  41. for (const file of files) {
  42. if (file.endsWith('.md')) {
  43. const filePath = join(markdownDir, file);
  44. await replaceImageLinksInFile(filePath);
  45. }
  46. }