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

複製代碼

複製代碼
const postDirPath = path.resolve(__dirname, "./source/_posts");
function main() {
const files = fs.readdirSync(postDirPath, {
withFileTypes: true
});
files.forEach(file => {
if (file.isFile()) replaceFile(file);
});
}
複製代碼
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));
});
}
複製代碼
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