Created
August 30, 2021 20:35
-
-
Save desi-programmer/eb9baa7c8ee00b7a24aa98bcbaa2d9ee to your computer and use it in GitHub Desktop.
Node JS Express JS Sending Streamed Response
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 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