Last active
July 15, 2018 08:07
blog-console-web-ui-animated-example
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
const express = require('express'); | |
const { Readable } = require('stream'); | |
// This is the special ANSI code to tell terminals to clear the screen | |
const PAGE_BREAK = '\033[2J\033[H'; | |
// This function gets the current date in string format along | |
// with a page break on top. | |
// Note that you would need to add a new line for the terminal to | |
// interpret it. That is `hello` will not work while `hello\n` will. | |
const getDate = () => ` | |
${PAGE_BREAK} | |
${new Date()} | |
`; | |
// This function initialises the stream for node | |
const getStream = (req, res) => { | |
const stream = new Readable(); | |
stream.pipe(res); | |
stream._read = () => {}; | |
req.on('close', () => { | |
stream.destroy(); | |
}); | |
return stream; | |
}; | |
// This is used to add delay between frames. | |
// Its just waits for a said millisec before resolving the promise | |
const delay = async (milliseconds = 0) => new Promise((resolve) => { | |
setTimeout(() => resolve(), milliseconds); | |
}); | |
// animateHello is the main function which pushes each frame | |
// of animation in a delay of 1sec (max 30 times) | |
const animateHello = async (stream) => { | |
for (let i = 0; i < 30; i += 1) { | |
stream.push(getDate()); | |
await delay(1000); | |
} | |
stream.push(null); //This ends the stream. | |
}; | |
// App initialisation | |
const app = express(); | |
// route | |
app.get('/anime-hello', async (req, res) => { | |
const stream = getStream(req, res); | |
await animateHello(stream); | |
}); | |
const PORT = process.env.PORT || 3000; | |
app.listen(PORT, () => console.log(`Example app listening on port ${PORT}!`)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment