Last active
December 21, 2023 12:57
-
-
Save mytharcher/889cc260376f4fcc8fbe619843c4f181 to your computer and use it in GitHub Desktop.
Download pasted images for md from Github
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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