在博客写作或文档整理中,经常需要插入大量图片到 Markdown 文件中。如果手动为每张图片编写 ![alt text](image_path) 格式的代码,既费时又容易出错。

脚本功能

这个脚本的核心功能是:

  • 扫描当前目录:识别常见图片格式(.jpg, .jpeg, .png, .gif, .bmp, .webp)。

  • 生成 Markdown 代码:为每张图片生成 ![alt text](image_path) 格式,其中 alt text 默认使用文件名(不含扩展名)。

  • 自定义路径前缀:支持通过命令行参数指定图片路径前缀,例如相对路径、绝对路径或 URL。

  • 输出结果:将生成的 Markdown 代码打印到控制台,并保存到 images.md 文件。

脚本代码

以下是完整的脚本代码:

const fs = require('fs').promises;
const path = require('path');

// 支持的图片文件扩展名
const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'];

// 检查文件是否为图片
function isImageFile(filename) {
  return imageExtensions.includes(path.extname(filename).toLowerCase());
}

// 生成 Markdown 图片插入格式
async function generateImageMarkdown(prefix = './') {
  try {
    // 确保前缀以斜杠结尾(规范化)
    const normalizedPrefix = prefix.endsWith('/') ? prefix : `${prefix}/`;

    // 获取当前目录
    const currentDir = process.cwd();
    // 读取目录中的所有文件
    const files = await fs.readdir(currentDir);

    // 过滤出图片文件
    const imageFiles = files.filter(isImageFile);

    if (imageFiles.length === 0) {
      console.log('当前目录下没有找到图片文件!');
      return;
    }

    // 生成 Markdown 格式
    const markdownLines = imageFiles.map(file => {
      const altText = path.basename(file, path.extname(file)); // 使用文件名(不含扩展名)作为 alt text
      return `![${altText}](${normalizedPrefix}${file})`;
    });

    // 输出到控制台
    console.log('生成的 Markdown 图片插入格式:');
    console.log(markdownLines.join('\n'));

    // 可选:写入到 markdown 文件
    const outputFile = 'images.md';
    await fs.writeFile(outputFile, markdownLines.join('\n'));
    console.log(`\n已将 Markdown 格式写入到 ${outputFile}`);
  } catch (error) {
    console.error('发生错误:', error.message);
  }
}

// 从命令行获取前置路径(默认 './')
const prefix = process.argv[2] || './';

// 执行函数
generateImageMarkdown(prefix);

如何使用

环境准备

  • 确保已安装 Node.js(运行 node -v 检查版本)。

  • 将脚本保存为 generateImageMarkdown.js

运行脚本

  1. 将脚本文件放入包含图片的目录。

  2. 打开终端,进入该目录,运行以下命令:

    node generateImageMarkdown.js [路径前缀]
    
    • [路径前缀] 是可选的,例如:

      • node generateImageMarkdown.js:使用默认前缀 ./

      • node generateImageMarkdown.js "https://example.com/images":使用 URL 前缀。

      • node generateImageMarkdown.js "../assets":使用相对路径前缀。

  3. 脚本会:

    • 扫描当前目录下的图片文件。

    • 生成 Markdown 格式的图片插入代码。

    • 将结果输出到控制台,并保存到 images.md 文件。

示例输出

假设目录中有 cat.jpgdog.png,运行以下命令:

node generateImageMarkdown.js "https://example.com/images"

控制台输出:

![cat](https://example.com/images/cat.jpg)
![dog](https://example.com/images/dog.png)

同时生成 images.md 文件,包含上述内容。

脚本亮点

  1. 灵活性:支持自定义路径前缀,适用于本地文件、GitHub 仓库或 CDN 链接。

  2. 自动化:自动识别图片文件,无需手动输入文件名。

  3. 健壮性:包含错误处理,若目录中无图片文件会提示用户。

  4. 易用性:只需一行命令即可生成所有图片的 Markdown 代码。