Skip to content

Instantly share code, notes, and snippets.

@acidg
Created February 3, 2017 12:46
Show Gist options
  • Save acidg/0404d69a34c1ed3b7b075e7ea44d5c91 to your computer and use it in GitHub Desktop.
Save acidg/0404d69a34c1ed3b7b075e7ea44d5c91 to your computer and use it in GitHub Desktop.
Node express application, runing a script and outputting results to browser in realtime
var cp = require("child_process");
var express = require("express");
var app = express();
var spw = null;
var lastTime = new Date();
app.get('/', function(req, res, next) {
var time = spw ? 'IN PROGRESS' : lastTime.toString();
res.send('<html>'
+ '<header>'
+ '<title>Update ASE Project</title>'
+ '</header>'
+ '<body>'
+ '<h3>Last update: ' + time
+ '<form action="/update" method="POST">'
+ '<button type="submit" id="update">Update</button>'
+ '</form>'
+ '</body>'
+ '</html>');
});
app.post('/update', function(req, res, next){
if (spw) {
res.send('Already updating, please wait');
return;
}
res.writeHead(200, { "Content-Type": "text/event-stream",
"Cache-control": "no-cache" });
spw = cp.spawn('./update.sh'),
spw.stdout.on('data', function (data) {
console.log(data.toString());
res.write(data);
});
spw.on('close', function (code) {
res.end('Done');
console.log('Done');
spw = null;
});
spw.stderr.on('data', function (data) {
console.log(data.toString());
res.write(data);
});
});
app.use(function(req, res, next) {
res.redirect('/');
});
app.listen(4000);
console.log('Listening on port 4000');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment