环境准备
安装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_type
和markdown
服务器将返回{status:0, data:"生成的文件路径"}
,通过返回文件相对路径进行下载即可
file_type
合法值有pdf
,png
,jpg
,html