Author: Li Jundong

scenario

All img SRC files in Markdown need to be signed by the server.

Train of thought

Since Markdown has syntax, first discard the regular scheme and search to see if there is an existing scheme.

Google javascript get all image in Markdown found get-md-image, a local try, found only the first image node in Markdown. In addition to obtaining images, the author also packages a series of libraries based on commonmark.js, and these libraries have a large number of NPM downloads.

Take a look at CommonMark.js, which is a library based on the JavaScript implementation of the Markdown standard provided in commonMark.js

The Parser method parses the Markdown string into a tree of nodes. The number of nodes contains basic data and some methods. We use type, destination, and walker() to get all image nodes

const commonMark = require("commonmark") const getAllImg = markdown => { if(! markdown) return let parsed = new commonMark.Parser().parse(markdown) let walker = parsed.walker() let event let srcList  = [] let nodeList = [] while (event = walker.next()) { let node = event.node; if ( node.type === "image" && node.destination ) { nodeList.push(node) } } const srcList = nodeList.map(node => node.destination) const uniqueSrcList = [...new Set(srcList)] return { srcList, uniqueSrcList, nodeList }; }Copy the code

Javascript gets all image nodes from Markdown