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
Output - How to create a streaming API in Node.js using Express - Clue Mediator
Steps to create a streaming API in Node.js
- Set up a new Node.js project
- Create an Express server
- Route to handle the streaming API
- Run the server
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:
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.
server.js
// 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..!! π