Skip to content

Instantly share code, notes, and snippets.

@luketn
Created August 8, 2020 02:02
Show Gist options
  • Save luketn/35ad55a6cbe1f05c1257b653b72ac3d7 to your computer and use it in GitHub Desktop.
Save luketn/35ad55a6cbe1f05c1257b653b72ac3d7 to your computer and use it in GitHub Desktop.
const child_process = require('child_process')
function run_script(command, args, realtimeCallback = (log, type) => {console.log(log)}) {
return new Promise((resolve) => {
let child = child_process.spawn(command, args)
let scriptOutput = ""
child.stdout.setEncoding('utf8')
child.stdout.on('data', function (data) {
realtimeCallback(data, 'stdout')
data = data.toString()
scriptOutput += data
})
child.stderr.setEncoding('utf8')
child.stderr.on('data', function (data) {
realtimeCallback(data, 'stderr')
data = data.toString()
scriptOutput += data
})
child.on('close', function (code) {
resolve({output: scriptOutput, code: code})
})
child.on('error', (code)=>{
resolve({output: scriptOutput, code: code})
})
})
}
async function runAndWriteOutputAsHtml(res, name, command, args) {
res.setHeader('Content-Type', 'text/html')
res.write(`<!doctype html><html><head><meta charset="UTF-8"><title>Run - ${name}</title></head><body><pre>`)
let result = await run_script(command, args, (log, type) => {
if (type === 'stderr') {
res.write('.')
} else {
res.write(`${log}\n`)
}
})
res.write('</pre>')
if (result.code!==0) {
res.write(`<p style="color: red">Process failed with code ${result.code}!</p><pre>\n${result.output}\n</pre>`)
}
res.write('</body></html>')
res.end()
}
@luketn
Copy link
Author

luketn commented Aug 8, 2020

Spawn a sub-process in NodeJS, attach to the stdout and stderr and wait for the process to close.
Write the stdout to a HTML page with '.' for the errors unless there is a non-0 exit code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment