Search code examples
node.jslatexmustache

Node.js render LaTeX code


I'm trying to execute the following code in Node.js:

var docdata = {paper_size: "a4paper", file: inFileName}
var output = Mustache.render("\documentclass[twoside]{article}\usepackage{pdfpages}\usepackage[{{paper_size}}]{geometry}\begin{document}\includepdf[pages=-]{{{file}}}\end{document}\batchmode", docdata);

But I'm receiving the following error:

var output = Mustache.render("\documentclass[twoside]\{article\}\usepackage\{
                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Unexpected token ILLEGAL
  at Module._compile (module.js:439:25)
  at Object.Module._extensions..js (module.js:474:10)
  at Module.load (module.js:356:32)
  at Function.Module._load (module.js:312:12)
  at Function.Module.runMain (module.js:497:10)
  at startup (node.js:119:16)
  at node.js:902:3

How should I escape the LaTeX string to render it correctly?


Solution

  • Replace all the backslashes with two backslashes \\, like

    "\\documentclass[twoside]{article}\\usepackage{pdfpages}\\usepackage[{{paper_size}}]{geometry}\\begin{document}\\includepdf[pages=-]{{{file}}}\\end{document}\\batchmode"

    Backslashes in string literals have special meaning, allowing you to escape characters like ", or add special characters, like newline \n. But this means that if you want an actual backslash, you have to escape it (with another backslash), like \\.