How to create a streaming API in Node.js using Express
In this article, we’ll show you how to create a streaming API in Node.js using Express. Here, we’ll stream the randomly generated string to create a streaming API.
Refer to the following article if you don’t know about the stream API:
Understanding Node.js Stream API: A Comprehensive Guide to Stream Processing in Node.js
Demo Application
Steps to create a streaming API in Node.js
1. Set up a new Node.js project
- Initialize a new Node.js project by running
npm init
in your project’s root directory. - Install Express by running
npm install express
.
2. Create an Express server
Create a new JavaScript file, e.g., server.js
, and require the necessary dependencies:
1 2 3 4 5 6 7 8 9 10 11 | const express = require('express'); const app = express(); ... ... const port = 3000; // Set the desired port number app.listen(port, () => { console.log(`Server is listening on port ${port}`); }); |
3. Route to handle the streaming API
Define the following route to handle the streaming API.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | // server.js const express = require('express'); const app = express(); app.get('/stream', (req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8', 'Transfer-Encoding': 'chunked', 'X-Content-Type-Options': 'nosniff' }); const interval = setInterval(() => { const data1 = Math.random().toString(36).substring(2, 8); const data2 = Math.random().toString(36).substring(2, 8); res.write(`${data1} ${data2}`); }, 100); setTimeout(() => { clearInterval(interval); res.end(); }, 10000); }); const port = 3000; app.listen(port, () => { console.log(`Server is listening on port ${port}`); }); |
4. Run the server
In the terminal, navigate to your project’s root directory and Run node server.js
to start the server.
Now, when you access http://localhost:3000/stream
in a web browser or make a request to that URL programmatically, the server will respond with a streaming API. In this example, the server streams the random text every 100 milliseconds. You can modify the streaming logic and response as per your requirements.
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂