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

出生場景

我的文章之前都是用簡書寫的,然而簡書的文章我復制到自己的博客上,圖片就顯示不出來。而且多篇文章,圖就更多了,我不可能一張一張替換吧。然后朋友就說,那你寫個腳本替換不就行了。然后就開始了。

舉個例子

  • 一般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:https://github.com/lingziyb/replace-img.git

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。