如何搭建自己的在线markdown转换器

环境准备

安装nodejs环境,下载地址

依赖包

express
@shd101wyy/mume

简易源码

// app.js
const express = require('express');
const mume = require("@shd101wyy/mume");
const path = require("path");
const bodyParser = require('body-parser');

const app = new express();

async function markdownToFile({markdown, fileType}){
  let config = {
    puppeteerArgs:['--no-sandbox',"--disable-setuid-sandbox"],
    previewTheme: "github-light.css",
    codeBlockTheme: "default.css",
    printBackground: true,
    enableScriptExecution: true,
    chromePath = "<填写你的chrome安装路径>"
  }
  await mume.init();
  let fileName = `${Date.now()}_${Math.random()}`;
  let dirPath = path.join(__dirname, "./public/attachments");
  let filePath = path.join(dirPath,fileName + ".md");
  fs.writeFileSync(filePath, markdown);
  const engine = new mume.MarkdownEngine({
    filePath,
    config
  })
  var res;
  if(fileType=='html'){
    res = await engine.htmlExport({offline: false, runAllCodeChunks:true});
  }else{
    res = await engine.chromeExport({fileType, runAllCodeChunks:true});
  }
  fs.unlink(filePath, res=>{
    console.log(res);
  });
  let url = "/attachments/" + path.basename(res);
  return url;
}

async function handleMarkdownConvertRequest({markdown, fileType="pdf"}){
  fileType = fileType.toLowerCase();
  const supportFileTypes = ["pdf", "png", "jpeg", "jpg", "html"]
  if(!markdown){
    return {status:-1, message:"markdown内容为空"}
  }
  if(supportFileTypes.indexOf(fileType)==-1){
    return {status:-2, message:"不支持的导出文件格式"}
  }
  let data = await markdownToFile({markdown, fileType});
  return {status:0, data}
}

app.get("/api/markdown_convert", async function(req, res){
  let {markdown, file_type:fileType="pdf"} = req.query;
  let json = await handleMarkdownConvertRequest({markdown, fileType});
  return res.json(json);
})

app.post("/api/markdown_convert", bodyParser.json(), async function(req, res){
  let {markdown, file_type:fileType="pdf"} = req.body;
  let json = await handleMarkdownConvertRequest({markdown, fileType});
  return res.json(json);
})

使用

向接口地址/api/markdown_convert发送get或post请求,请求参数为file_typemarkdown
服务器将返回{status:0, data:"生成的文件路径"},通过返回文件相对路径进行下载即可

  • file_type合法值有pdf,png,jpg,html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值