const fs = require('fs'); const spawn = require('child_process').spawn; const uuid = require('uuid'); const {getDirPath, getDocPath} = require('./utils'); function copyToTemp(id, texDocument, callback) { const dirPath = getDirPath(id); fs.mkdir(dirPath, (err) => { if (err) { callback(err); return; } const docPath = getDocPath(id); fs.writeFile(docPath, texDocument, (err) => { if (err) { callback(err); } callback(null); }); }); } function generateDoc(id, callback) { const pdflatex = spawn('pdflatex', [getDocPath(id), '-interaction', 'nonstopmode'], {cwd: getDirPath(id)}); pdflatex.stderr.on('data', (data) => { console.error('onData', data); }); pdflatex.on('close', (code) => { if (code > 0) { callback(`pdflatex returned with code ${code}`); return; } console.log(`PDF ${id} generated`); callback(null, id); }); } module.exports = (texDocument, callback) => { const id = uuid.v1(); copyToTemp(id, texDocument, (err) => { if (err) { callback(err); return; } generateDoc(id, callback); }); };