Skip to content

Instantly share code, notes, and snippets.

@domachine
Created May 30, 2016 15:21
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 domachine/8cc1eea83821ad78239b52f6c51cd762 to your computer and use it in GitHub Desktop.
Save domachine/8cc1eea83821ad78239b52f6c51cd762 to your computer and use it in GitHub Desktop.
webdesignio Secure rendering of components on the server side
'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