Tips for sending live data to the client by writing multiple responses in Node.js using res.write

I am looking to continuously send data to the client in real-time from res.write, however, the current setup only allows for sending data once in one response. How can I modify this code to enable multiple responses and ensure the data is streamed live to the client?

app.get('/api/simulator', (req,res) => {

    res.setHeader('Content-Type','text/html');
    var spawn = require('child_process').spawn,
ls = spawn('../abc.sh');

ls.stdout.on('data', function (data) {
  console.log('stdout: ' + data.toString());
  res.write(data.toString());
});

ls.stderr.on('data', function (data) {
  console.log('stderr: ' + data.toString());
});

ls.on('exit', function (code) {
    console.log('child process exited with code ' + code.toString());
    res.end();
  });

});

Answer №1

One way to include additional content in a response is by using res.write() function. Here's an example:

ls.stdout.on('data', function (data) {
  console.log('stdout: ' + data.toString());
  res.write(data.toString());
  res.write("foo");
  res.write("bar");
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best location to store reusable backend scripts in a Node.js project?

In my Nodejs project, I am working on creating a JavaScript file that is not a middleware. This file will contain a function that takes a value as input and produces an output using module.exports. I am currently deciding on the best location to store this ...

Facing difficulties in resetting the time for a countdown in React

I've implemented the react-countdown library to create a timer, but I'm facing an issue with resetting the timer once it reaches zero. The timer should restart again and continue running. Take a look at my code: export default function App() { ...

Turning off arrow key navigation for tabs in Material UI ReactJS

I'm currently utilizing ReactJS Material UI tabs navigation. My aim is to deactivate the arrow keys navigation of Tabs in Material UI. What I desire is to navigate using the Tab key, and upon pressing Enter, it should display the page beneath that ta ...

Tips for retrieving nested documents in MongoDB

Is there a way to fetch specific nested elements from a Mongo Collection? My goal is to retrieve data for sem-1, but I'm currently getting all the information under a particular student id. If you need more context on the MongoDB structure, you can c ...

I aim to continuously refresh a dynamic canvas line chart with JSON data

Having trouble with my code - the chart isn't updating. I'm new to using canvasJS charts and could use some help. <%@ page language=”java” contentType=”text/html; charset=UTF-8″ pageEncoding=”UTF-8″%> <%@ page import=”java ...

What is the best way to offer users the option to download files through my Node.js Rest API?

Initially, I am unsure about the best way to provide files for users to download on my website. Is it possible to use the API to retrieve and send files to users? If so, what would be the correct method to accomplish this task? ...

Tips on modifying the style of a specific React component without affecting the others

In my attempt to modify a single style property of a specific React component upon clicking it, I encountered an issue where the changes applied to every instance of that component. Despite consulting the React tutorial and various sources for solutions, I ...

The mysterious case of the missing CSS file in Node.js

I recently set up a new Node.js Express Project. However, I am facing an issue with the index.ejs file showing the error: Undefined CSS file ('/stylesheets/style.css'). Here is the content of the index.ejs file: <!DOCTYPE html> <html& ...

What is the logic behind using interfaces to declare functions in TypeScript and what exactly is the purpose behind it?

interface SearchFunc { (source: string, subString: string): boolean; } It is common for me to define a function in this manner: type Search = (source:string,subString:string)=>void I am curious about why TypeScript allows the use of interfaces to de ...

What steps can be taken to adjust the alignment of a Bootstrap Dropright menu so that it opens in an upward direction instead of the standard downward

My dropdown menu is dropping towards the right correctly, but it is going downwards and getting hidden under my page. I want it to open upwards instead of downwards. I attempted to adjust the CSS, adding bottom:0 to the dropdown-menu, but unfortunately, i ...

Is your WordPress Gutenberg PluginDocumentSettingPanel malfunctioning with its controls?

I recently sought to enhance the gutenberg document panel by incorporating a custom meta field, using this informative documentation. To create the desired custom meta field, I referred to this useful tutorial. The challenge arises when attempting to merge ...

Ways to conceal a form post-submission

Looking for help with a programming issue - I'm trying to hide a form after submitting form data to prevent multiple submissions. The forms are created dynamically and I've tried hiding both the form and the div it's inside without success. ...

Guide to retrieving a .txt file from a separate domain using server-side JavaScript and transferring it to the client side

My goal is to retrieve a .txt file from a web server on a different domain that does not have CORS or web services enabled. I believe I will need to handle this task on the server side using Node.js and JQuery, but I am unsure of where to begin. Currently, ...

Security Concerns with AngularJS Role-Based Menu Display

Being new to MEAN.js, I am currently working on an application that has two roles - User and Admin. I need to display a menu based on the user role. Below is the header file I have created for both admin and user roles: <ul class="nav navbar-nav navbar ...

I attempted to use ng add @angular/pwa, but encountered an error code that is baffling to me. Are there any steps I can take to resolve this issue?

npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While trying to find a solution: [email protected] npm ERR! Found: @angular/[email protected] npm ERR! in node_modules/@angular/common npm ERR! @angular/common@"^14.2.3" ...

Using Font Color in Gmail HTML Emails

While working on styling an HTML email, I've encountered an unexpected issue with inline CSS in Gmail. I set the color of text in a table row using the following code: <tr style='color: #000; font-size: 14px; font-family: Verdana, serif;' ...

When a Material-UI styled component is displayed in an indigo color, even if that specific color was

I'm currently working on building a NextJS application using Material-UI, taking inspiration from a boilerplate I stumbled upon at https://github.com/phuongnq/nextjs-material-design-boilerplate. You can take a look at my own implementation at https:/ ...

I am having trouble with searching for places using the Google API in my Node

Recently, I've been working on integrating the Google Maps API places feature into my project. Thankfully, I came across an npm module that simplifies the process of connecting it to node. Check out the npm module here! After downloading the module ...

The radar chart created with amchart.js disappears when placed within bootstrap columns

I'm encountering an issue while trying to display radar charts using amchart.js in bootstrap columns. The "amStockGraph" charts render perfectly, however, the radar charts appear blank with no errors in the console. Any advice on this matter would be ...

Is adjusting a ref's value during render instead of using useEffect a secure practice?

Utilizing the useRef hook, I am storing the most recent value of a prop to access later in an async callback like an onClick handler. Instead of adding 'value' to the useCallback dependencies list, I opted for a ref since I anticipate frequent ch ...