Created
May 30, 2016 15:21
-
-
Save domachine/8cc1eea83821ad78239b52f6c51cd762 to your computer and use it in GitHub Desktop.
webdesignio Secure rendering of components on the server side
This file contains 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 fs = require('fs') | |
const vm = require('vm') | |
const cluster = require('cluster') | |
const shortid = require('shortid') | |
if (cluster.isMaster) { | |
// Act as master | |
cluster.on('online', worker => { | |
console.log('[master]: worker is online') | |
const taskIds = [shortid()] | |
const componentResults = [] | |
worker.on('message', ({ id, result }) => { | |
console.log('[master]: message received') | |
console.log(result) | |
componentResults[taskIds.indexOf(id)] = result | |
process.exit(0) | |
}) | |
worker.send({ id: taskIds[0], component: 'component' }) | |
}) | |
cluster.fork() | |
} else { | |
// Act as worker | |
process.on('message', ({ id, component }) => { | |
console.log('[worker]: message received') | |
const componentPath = require.resolve(`./components/${component}`) | |
const src = fs.readFileSync(componentPath) | |
const module = { exports: {}, global: {} } | |
const context = vm.createContext({ exports: module.exports, module }) | |
vm.runInContext(src + '\n\n__OUT__ = module.exports.renderToString()', context) | |
console.log('[worker]: send back result') | |
process.send({ id, result: context.__OUT__ }) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment