Pandoc As A Service
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

server.js 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. let fs = require("fs");
  2. let http = require("http");
  3. let pathlib = require("path");
  4. let spawn = require("child_process").spawn;
  5. let tmp = require("tmp");
  6. function processPandoc(req, res) {
  7. let tmpf = tmp.fileSync({ postfix: ".pdf" });
  8. let child = spawn("pandoc",
  9. [ "--standalone", "--output", tmpf.name ]);
  10. child.on("error", err => {
  11. res.writeHead(500);
  12. res.end(JSON.stringify({ output: err.toString() }));
  13. tmpf.removeCallback();
  14. });
  15. let output = "";
  16. child.stdout.on("data", d => output += d.toString());
  17. child.stderr.on("data", d => output += d.toString());
  18. child.on("exit", (code, sig) => {
  19. if (code === 0) {
  20. res.end(JSON.stringify({
  21. pdf: fs.readFileSync(tmpf.name).toString("base64"),
  22. output
  23. }));
  24. tmpf.removeCallback();
  25. } else {
  26. res.end(JSON.stringify({ output }));
  27. tmpf.removeCallback();
  28. }
  29. });
  30. req.pipe(child.stdin);
  31. }
  32. function mime(path) {
  33. if (path.endsWith(".html"))
  34. return "text/html";
  35. if (path.endsWith(".css"))
  36. return "text/css";
  37. if (path.endsWith(".js"))
  38. return "application/javascript";
  39. return "application/octet-stream";
  40. }
  41. function serve(url, res) {
  42. let path = pathlib.join(__dirname, "web", url);
  43. let rs = fs.createReadStream(path);
  44. rs.once("error", err => {
  45. if (err.code == "ENOENT") {
  46. res.writeHead(404);
  47. res.end("404 Not Found");
  48. } else {
  49. res.writeHead(500);
  50. res.end("500 Internal Server Error");
  51. console.error(err);
  52. }
  53. });
  54. rs.once("open", () => {
  55. res.writeHead(200, {
  56. "Content-Type": mime(path)
  57. });
  58. rs.pipe(res);
  59. });
  60. }
  61. let server = http.createServer((req, res) => {
  62. if (req.url == "/") {
  63. serve("/index.html", res);
  64. } else if (req.method == "POST" && req.url == "/pandoc") {
  65. processPandoc(req, res);
  66. } else {
  67. serve(req.url, res);
  68. }
  69. });
  70. let port = process.env.PORT || 8080;
  71. server.listen(port, "127.0.0.1");
  72. console.log("Listening to 127.0.0.1:" + port);