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

- 替換之后它長這樣的:

實現步驟
- 循環文件夾,找到文件夾里所有要替換圖片的md文件。
- 讀取md文件內容。
- 正則匹配圖片路徑。
- 下載圖片。
- 保存圖片到本地目錄。
- 替換成相對路徑。
具體實現
- 循環文件夾,找到文件夾里所有要替換圖片的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