Last active
July 22, 2016 20:24
-
-
Save avnersorek/cf395cc6ec205cde2a71572b7247df8c to your computer and use it in GitHub Desktop.
Calling 3rd party in a new process
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const cp = require('child_process'); | |
const showdown = require('showdown'); | |
const config = require('my-config'); | |
const requestTimeout = config.get('app:requestTimeoutMs'); | |
const converter = new showdown.Converter(); | |
// in the master process | |
function markdownToHtml(markdown) { | |
return new Promise((resolve, reject) => { | |
const child = cp.fork(module.filename); // forking this module | |
child.on('error', reject); | |
let parseTimeout = setTimeout(() => { | |
child.kill(); | |
reject(new Error('markdown timeout')); | |
}, requestTimeout); | |
child.on('message', message => { | |
clearTimeout(parseTimeout); | |
resolve(message.parsed); | |
}); | |
child.send({ markdown }); | |
}); | |
} | |
// in the child process | |
process.on('message', function (message) { | |
try { | |
let parsed = converter.makeHtml(message.markdown); | |
process.send({ parsed }); | |
process.exit(); | |
} | |
catch (err) { | |
process.exit(-1); | |
} | |
}); | |
module.exports = { | |
markdownToHtml | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment