Skip to content

Instantly share code, notes, and snippets.

@joewright
Last active December 19, 2018 19:36
Show Gist options
  • Save joewright/6bec2fed8bfa9abc9422cca1c223ffe2 to your computer and use it in GitHub Desktop.
Save joewright/6bec2fed8bfa9abc9422cca1c223ffe2 to your computer and use it in GitHub Desktop.
Stream html responses
const http = require('http');
const port = 3000;
const hostname = '127.0.0.1';
const max = 25;
const delay = 200;
const htmlOpen = `
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="Demo project">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Here we go!</h1>
<ul>`;
const htmlClose = `
</ul>
<marquee behavior="alternate" direction="right">All done!</marquee>
</body>
</html>`;
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/') {
return getIndex(req, res);
}
return res.end('Wow');
});
//wait for a connection
server.listen(port, hostname, () => {
console.log(`Listening @ port ${port}`);
});
function getIndex(req, res) {
//set the appropriate HTTP header
res.setHeader('Content-Type', 'text/html');
res.write(htmlOpen);
nextItem(1);
//send multiple responses to the client
function nextItem(count) {
res.write(`<li>Count: ${count}</li>`);
if (count === max) {
//end the response process
return res.end(htmlClose);
}
setTimeout(function() {
count++;
nextItem(count);
}, delay);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment