-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
76 lines (60 loc) · 2.04 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
const express = require('express');
const { marpCli } = require('@marp-team/marp-cli');
const puppeteer = require('puppeteer');
const fs = require('fs').promises;
const os = require('os');
const path = require('path');
const app = express();
app.use(express.json());
let browser;
async function initializeBrowser() {
browser = await puppeteer.launch({
args: ['--no-sandbox', '--disable-setuid-sandbox'],
});
}
initializeBrowser();
app.post('/convert', async (req, res) => {
const { markdown, outputFormat, options = [] } = req.body;
if (!markdown || !outputFormat) {
return res.status(400).json({ error: 'Missing markdown or outputFormat' });
}
try {
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'marp-'));
const inputFile = path.join(tmpDir, 'input.md');
const outputFile = path.join(tmpDir, `output.${outputFormat}`);
await fs.writeFile(inputFile, markdown);
const cliOptions = [
inputFile,
'--output', outputFile,
`--${outputFormat}`,
'--html',
'--allow-local-files',
'--puppeteer-launch-args', '["--no-sandbox", "--disable-setuid-sandbox"]',
'--puppeteer-browser-executable', await browser.executablePath(),
...options
];
if (outputFormat === 'pdf' || outputFormat === 'pptx') {
cliOptions.push(`--${outputFormat}-notes`);
cliOptions.push(`--${outputFormat}-delay`, '3000');
}
await marpCli(cliOptions);
const output = await fs.readFile(outputFile);
await fs.rm(tmpDir, { recursive: true });
res.contentType(outputFormat);
res.send(output);
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Conversion failed' });
}
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Marp API server listening on port ${port}`);
});
process.on('SIGTERM', async () => {
console.log('SIGTERM signal received: closing HTTP server');
if (browser) {
await browser.close();
}
process.exit(0);
});