Created
August 8, 2020 02:02
-
-
Save luketn/35ad55a6cbe1f05c1257b653b72ac3d7 to your computer and use it in GitHub Desktop.
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
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() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.