Born scenario

I used to write all my posts in Jane, but the pictures didn’t show up when I copied Jane’s posts to my blog. And with more articles, there are more pictures. I can’t replace them one by one. And the friend said, well, why don’t you just write a script instead. And then it started.

For example

  • General MD pictures look like this:
! [Lottery table](http://upload-images.jianshu.io/upload_images/3453108-d3d4ecbe2309e96e.png? imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)Copy the code
  • After substitution it looks like this:
! [Lotto wheel](./1.jpg)Copy the code

Implementation steps

  1. Loop through the folder and find all the MD files in the folder that you want to replace images with.
  2. Read the contents of the MD file.
  3. The re matches the image path.
  4. Download pictures.
  5. Save the image to a local directory.
  6. Replace it with a relative path.

The specific implementation

  • Loop through the folder and find all the MD files in the folder that you want to replace images with:
const postDirPath = path.resolve(__dirname, "./source/_posts");

function main() {
  const files = fs.readdirSync(postDirPath, {
    withFileTypes: true
  });

  files.forEach(file => {
    if (file.isFile()) replaceFile(file);
  });
}
Copy the code
  • Read the contents of the MD file.
const filePath = path.resolve(postDirPath, file.name);
const fileData = fs.readFileSync(filePath, "utf8");
Copy the code
  • The re matches the image path.
const regex = /\! \[.*\]\((http.*)\)/;if(! regex.exec(fileData))return;
const url = regex.exec(fileData)[1];
Copy the code
  • Download pictures.

function download(url) {
  return new Promise((resolve, reject) => {
    const HTTP = url.includes("http://")? http : https; HTTP.get(url, response => {let imgData = "";
      response.setEncoding("binary"); // Some HTTP linked images need to be redirected to HTTPSif (response.statusCode == 301) download(response.headers.location);

      response.on("data", chunk => (imgData += chunk));
      response.on("end", () => {
        resolve(imgData);
      });
    }).on("error", err => reject(err));
  });
}
Copy the code
  • Save the image to a local directory. As there are many pictures in an MD article, the names of the pictures are as follows: 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");
}
Copy the code
  • Replace it with a relative path
function replace(filePath, imgFileName, url) {
  const fileData = fs.readFileSync(filePath, "utf8");
  const newFile = fileData.replace(url, `./${imgFileName}.jpg`);
  fs.writeFileSync(filePath, newFile);
}
Copy the code

Finally:

See Lingzi’s github for details: github.com/lingziyb/re…