Created
March 29, 2023 08:20
-
-
Save dsathyakumar/bc0c0c2ef64d14b040f005a710f72f63 to your computer and use it in GitHub Desktop.
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
require('marko/node-require').install(); | |
var EventEmitter = require('events').EventEmitter; | |
const http = require('http'); | |
const server = require('http').createServer(); | |
const port = 8080; | |
/** | |
* This function serves like an SSE end point which pushes data. | |
* Data is emitted in chunks here. | |
*/ | |
function getDataEmitter() { | |
var ee = new EventEmitter(); | |
var i = 0; | |
function getData(){ | |
i = i + 1; | |
ee.emit('data', i); | |
if (i < 5) { | |
setTimeout(getData, 1000); | |
} else { | |
ee.emit('end'); | |
} | |
} | |
process.nextTick(getData); | |
return ee; | |
} | |
server.on('request', (req, res) => { | |
var out = require('async-writer').create(res); | |
var asyncOut = out.beginAsync({ | |
timeout: 0 | |
}); | |
var dataEmitter = getDataEmitter(); | |
asyncOut.write('<h1>Hello world!</h1>'); | |
dataEmitter.on('data', function (data) { | |
console.log('data!'); | |
asyncOut.write('<h3>'+data+'</h3>'); | |
asyncOut.flush(); | |
}); | |
dataEmitter.on('end', function () { | |
asyncOut.end(); | |
}); | |
asyncOut.write('<h1>Bye world</h1>'); | |
out.end(); | |
}); | |
server.listen(port, () => { | |
console.log(`Successfully started server on port ${port}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment