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

- 替換之后它長這樣的:

實(shí)現(xiàn)步驟
- 循環(huán)文件夾,找到文件夾里所有要替換圖片的md文件。
- 讀取md文件內(nèi)容。
- 正則匹配圖片路徑。
- 下載圖片。
- 保存圖片到本地目錄。
- 替換成相對(duì)路徑。
具體實(shí)現(xiàn)
- 循環(huán)文件夾,找到文件夾里所有要替換圖片的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文件內(nèi)容。
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));
});
}
- 保存圖片到本地目錄。因?yàn)橐黄猰d文章里有很多張圖片,所以簡單粗暴點(diǎn),圖片名稱依次為: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");
}
- 替換成相對(duì)路徑
function replace(filePath, imgFileName, url) {
const fileData = fs.readFileSync(filePath, "utf8");
const newFile = fileData.replace(url, `./${imgFileName}.jpg`);
fs.writeFileSync(filePath, newFile);
}
最后:
詳細(xì)代碼請(qǐng)查看lingzi的github:https://github.com/lingziyb/replace-img.git