Skip to content

Instantly share code, notes, and snippets.

@desi-programmer
Created August 30, 2021 20:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save desi-programmer/eb9baa7c8ee00b7a24aa98bcbaa2d9ee to your computer and use it in GitHub Desktop.
Save desi-programmer/eb9baa7c8ee00b7a24aa98bcbaa2d9ee to your computer and use it in GitHub Desktop.
Node JS Express JS Sending Streamed Response
const express = require('express');
const cors = require('cors');
const app = express();
app.use(express.json({ extended: true }));
app.use(cors());
// use browser to see the response
app.get('/stream', (req, res) => {
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.setHeader('Transfer-Encoding', 'chunked');
res.write("USERID,NAME,FBID,ACCOUNT,SUBSCRIPTION,PRICE,STATE,TIMEPERIOD\n");
sendAndSleep(res, 1);
});
var sendAndSleep = function (response, counter) {
if (counter > 100) {
response.end();
} else {
response.write(" ;i=" + counter);
counter++;
setTimeout(function () {
sendAndSleep(response, counter);
}, 1000)
};
};
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server Started at PORT : ${PORT}`),);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment