个人文章以前都是用简书写的,然而简书的文章我复制到本身的博客上,图片就显示不出来。并且多篇文章,图就更多了,我不可能一张一张替换吧。而后朋友就说,那你写个脚本替换不就好了。而后就开始了。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