使用Joplin作为博客后端-使用marked转换joplin笔记中资源文件的地址

joplin笔记中资源文件默认使用的是id,但是如果渲染到网页,需要转换为网络地址,记录一下处理过程。

export async function transformMarkdown(markdown?: string) {
    if (markdown == null || markdown === '') {
        return ''
    }

    const renderer = new marked.Renderer()

    marked.use({
        async: true,
        async walkTokens(token) {
            if (token.type === "image") {
                const id = token.href.replace(':/', '')
                const resource = await joplinResource(id)
                token.href = `${process.env.SITE_URL}/resources/${id}.${resource.file_extension}`
                token.title = resource.title
            }
        },
        renderer: {
            image({ href, text, title }) {
                return `${text}`
            }
        }
    })

    return await marked.parse(markdown, {
        renderer,
        gfm: true,
        breaks: false,
        pedantic: false
    })
}
文章标签