把md文檔中的圖片地址換成相對地址

出生場景

個人文章以前都是用簡書寫的,然而簡書的文章我複製到本身的博客上,圖片就顯示不出來。並且多篇文章,圖就更多了,我不可能一張一張替換吧。而後朋友就說,那你寫個腳本替換不就好了。而後就開始了。git

舉個例子

  • 通常md圖片都長這樣的:
![抽獎轉盤](http://upload-images.jianshu.io/upload_images/3453108-d3d4ecbe2309e96e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
複製代碼
  • 替換以後它長這樣的:
![抽獎轉盤](./1.jpg)
複製代碼

實現步驟

  1. 循環文件夾,找到文件夾裏全部要替換圖片的md文件。
  2. 讀取md文件內容。
  3. 正則匹配圖片路徑。
  4. 下載圖片。
  5. 保存圖片到本地目錄。
  6. 替換成相對路徑。

具體實現

  • 循環文件夾,找到文件夾裏全部要替換圖片的md文件:
const postDirPath = path.resolve(__dirname, "./source/_posts");

function main() {
  const files = fs.readdirSync(postDirPath, {
    withFileTypes: true
  });

  files.forEach(file => {
    if (file.isFile()) replaceFile(file);
  });
}
複製代碼
  • 讀取md文件內容。
const filePath = path.resolve(postDirPath, file.name);
const fileData = fs.readFileSync(filePath, "utf8");
複製代碼
  • 正則匹配圖片路徑。
const regex = /\!\[.*\]\((http.*)\)/;

if (!regex.exec(fileData)) return;
const url = regex.exec(fileData)[1];
複製代碼
  • 下載圖片。
function download(url) {
  return new Promise((resolve, reject) => {
    const HTTP = url.includes("http://") ? http : https;
    HTTP.get(url, response => {
      let imgData = "";
      response.setEncoding("binary");

      // 有些http連接的圖片 須要重定向到HTTPS
      if (response.statusCode == 301) download(response.headers.location);

      response.on("data", chunk => (imgData += chunk));
      response.on("end", () => {
        resolve(imgData);
      });
    }).on("error", err => reject(err));
  });
}
複製代碼
  • 保存圖片到本地目錄。由於一篇md文章裏有不少張圖片,因此簡單粗暴點,圖片名稱依次爲:1.jpg、2.jpg、3.jpg...
function saveImg(dirName, imgFileName, imgData) {
  const dirPath = path.resolve(postDirPath, dirName);
  if (!fs.existsSync(dirPath)) fs.mkdirSync(dirPath);
  fs.writeFileSync(`${dirPath}/${imgFileName}.jpg`, imgData, "binary");
}
複製代碼
  • 替換成相對路徑
function replace(filePath, imgFileName, url) {
  const fileData = fs.readFileSync(filePath, "utf8");
  const newFile = fileData.replace(url, `./${imgFileName}.jpg`);
  fs.writeFileSync(filePath, newFile);
}
複製代碼

最後:

詳細代碼請查看lingzi的github:github.com/lingziyb/re…github

相關文章
相關標籤/搜索