Skip to content

Instantly share code, notes, and snippets.

@tiarno
Created February 18, 2015 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiarno/fda72a65404f5677f5c4 to your computer and use it in GitHub Desktop.
Save tiarno/fda72a65404f5677f5c4 to your computer and use it in GitHub Desktop.
NodeJS server receives LaTeX, returns SVG
var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;
var createServer = function(port) {
var mjAPI = require("node_modules/MathJax-node/lib/mj-single");
mjAPI.config({
MathJax: {
SVG: {
font: "STIX-Web"
},
displayAlign: "left",
displayIndent:"3em",
tex2jax: {
preview: ["[math]"],
processEscapes: true,
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
skipTags: ["script","noscript","style","textarea","pre","code"]
},
TeX: {
noUndefined: {disabled: true},
Macros: {
mb:['{\\mathbf{#1}}',1],
mbox: ['{\\text{#1}}',1],
mc: ['{\\mathcal{#1}}',1],
mi: ['{\\mathit{#1}}',1],
mr: ['{\\mathrm{#1}}',1],
ms: ['{\\mathsf{#1}}',1],
mt: ['{\\mathtt{#1}}',1],
rule: ['{}',2],
textup: ['{\\mathrm{#1}}',1]
}
}
}
});
mjAPI.start();
var server = http.createServer(function (request, response) {
var str_params = '';
request.on('data', function(chunk){str_params += chunk;});
request.on('end', function(){
var params = JSON.parse(str_params);
mjAPI.typeset(params, function(result){
// console.log('typesetting with ' + params.math);
if (!result.errors) {
response.writeHead(200, {'Content-Type': 'image/svg+xml'});
if (params.svg) {response.end(result.svg);}
else{response.end(result.mml);}
} else {
response.writeHead(400, {'Content-Type': 'text/plain'});
response.write('Error 400: Request Failed. \n');
response.write(String(result.errors) + '\n');
response.write(str_params + '\n');
response.end();
}
});
});
});
server.listen(port, function(){
console.log('Server listening on port %s' , port);
});
return server;
};
if (cluster.isMaster) {
// Fork workers.
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died');
});
} else {
var server = createServer(8000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment