Skip to content

Instantly share code, notes, and snippets.

@mytharcher
Last active December 21, 2023 12:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mytharcher/889cc260376f4fcc8fbe619843c4f181 to your computer and use it in GitHub Desktop.
Save mytharcher/889cc260376f4fcc8fbe619843c4f181 to your computer and use it in GitHub Desktop.
Download pasted images for md from Github
const fs = require('node:fs');
const fsPromise = require('node:fs/promises');
const { https } = require('follow-redirects');
const { glob } = require('glob');
async function download(url, toFile) {
const file = fs.createWriteStream(toFile);
await new Promise((resovle, reject) => {
console.log('downloading file:', url);
https.get(url, (response) => {
response.pipe(file);
});
file.on("finish", () => {
file.close();
console.log("Download Completed");
resovle();
});
});
}
async function run() {
const mds = await glob('**/*.md', { ignore: ['node_modules/**'] });
const re = /^(\s*!\[[^\]]*\])\((https\:\/\/github\.com.*)\)/;
for (const f of mds) {
const file = await fsPromise.open(f);
const content = [];
let changed = false;
for await (const line of file.readLines()) {
const matcher = line.match(re);
if (matcher) {
changed = true;
const imgFileName = matcher[2].split('/').pop();
const imgFilePath = `${f.replace(/\/[^/]+\.md$/, '/')}${imgFileName}.png`;
await download(matcher[2], imgFilePath);
content.push(`${matcher[1]}(./${imgFileName}.png)`);
} else {
content.push(line);
}
}
if (changed) {
content.push('\n');
await fsPromise.writeFile(f, content.join('\n'));
console.log('file resovled:', f);
}
}
}
run()
.then(() => {
console.log('done');
process.exit(0);
})
.catch((err) => {
console.error(err);
process.exit(1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment