Ensuring Node.js backend JavaScript waits for completion of my bash script before proceeding

Running three bash commands through a Node.js code snippet. Here's a portion of the script:

exec(str,
function(error, stdout, stderr){
    console.log('stdout:'+stdout);
    console.log('stderr:'+stderr);
    if(error!=null){
        console.log('exec error: '+error);
    }
exec('bash create_q_out_list.sh',
    function(error, stdout, stderr){
        console.log('stdout:'+stdout);
        console.log('stderr:'+stderr);
        if(error!=null){
            console.log('exec error: '+error);
        }
exec('bash replaceString.sh',
    function(error, stdout, stderr){
        console.log('stdout:'+stdout);
        console.log('stderr:'+stderr);
        if(error!=null){
            console.log('exec error: '+error);
        }
        });
    });
});

The 'bash replaceString.sh' command generates an HTML file that is displayed in an Iframe on my website's homepage. However, there are instances where the old file is shown before the new one is fully generated by the 3rd bash command. This results in displaying incorrect content even though the correct HTML content is present.

Below is the Iframe section:

<iframe id='svg_frame' src="http://127.0.0.1:3000/render.html"></iframe>

Additionally, here is a segment of my server code (render.html is the file being created by the 3rd bash command):

app.get('/render.html', (req, res) =>{
  const rend = fs.readFileSync('./render.html');
  res.statusCode = 200;
  res.setHeader = ('Content-Type', 'text/html');
  res.write(rend);
  res.end();
});

I need to ensure that the Node.js script waits for the new render.html file to be completely generated before rendering it on the Iframe.

Answer №1

After considering @Plixxer's point of view, I tend to agree that for a simple task like replacing a string, sticking with JavaScript on node is the way to go. However, it seems like the issue lies in

app.get('/render.html', (req, res) =>{
  const rend = fs.readFileSync('./render.html');
  res.statusCode = 200;
  res.setHeader = ('Content-Type', 'text/html');
  res.write(rend);
  res.end();
});

specifically at

const rend = fs.readFileSync('./render.html');

If the file already exists before you make any replacements with your bash script, node will simply retrieve it from the file system and serve it to the client without being aware of any background changes. This means you should perform the replace operation within the app.get() block:


app.get('/render.html', (req, res) =>{
  let rend = fs.readFileSync('./render.html');
  rend = rend.replace('<regex or whatever you are replacing in bash>', '<replacement, can also be a function!>');
  // Alternatively, you can execute your bash replacement script here!
  //   exec('bash replaceString.sh', rend,
  //     function(error, stdout, stderr) {
  //       console.log('stdout:', stdout);
  //       console.log('stderr:', stderr);
  //       if (error !== null) {
  //           console.log('exec error:', error);
  //       }
  //     }
  //   );
  res.statusCode = 200;
  res.setHeader = ('Content-Type', 'text/html');
  res.write(rend);
  res.end();
});

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

Node JS Promise does not provide a value as a return

Struggling with getting a value back from the code snippet below, even though it console logs out without any issues. Any suggestions on how to assign a value to X? var dbSize = dbo.collection('Items').count() var x = 0 x = dbS ...

React Component that closes when it loses focus

In my React project, I am working on creating a custom select2 style component. Most of the functionality is complete, but I am struggling with figuring out how to hide the result box when the user clicks away. Here is the render method: render() { l ...

Creating mocks for request handler next function in ExpressJS using Mocha

I am currently using a handler that ensures authentication public ensureAuthenticated(req: express.Request, res: express.Response, next: Function) { // check header or url parameters or post parameters for token var token = req.body.token || req ...

Guide on handling 404 page redirection within an axios service in Next.js

Currently, I am utilizing axios to handle my API calls. One thing that I want to achieve is checking the status of the response received from the api and potentially redirecting to a 404 page based on that. const api = axios.create({ headers: { commo ...

Looking for a specific phrase in the data entered by the user

I am dealing with data in ckeditor that looks like this: <p>test 1</p> <p>test 2</p> <p><img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICw ...

Calling a JavaScript function from server-side code (without using startup scripts)

In essence, my objective is as follows: Initiate deletion of a record upon button click. Delete the record only if a specific column (Location) is null (working perfectly). If the specific column is not null, prompt the user for confirmation before proce ...

Storing Images in MongoDB with the MEAN Stack: A Guide using Node.js, Express.js, and Angular 6

I am currently working on developing a MEAN Shop Application, and I have encountered an error while attempting to store the product image in MongoDB. typeError: cannot read the property 'productimage' of undefined Below is the route function fo ...

Is it possible to send multiple HTML input values to a Google Spreadsheet using only JavaScript?

Seeking a faster and more efficient way to send the values of multiple HTML Inputs to a specific location in a Google Spreadsheet? The existing script takes too long to complete, often skips inputs, and relies heavily on "google.script.run". Due to softwar ...

Executing tasks in a While loop with NodeJS and attaching actions to a Promise

I am relatively new to incorporating Promises in NodeJS. My current task involves creating a promise dynamically with multiple actions based on the characters found in a string. //let actions = []; getPromise = get(srcBucket, srcKey); // Retrieve the imag ...

Received a Vue prop as a variable name, rather than the actual string value it represents

In the parent component, my string variable is being passed down. The constant GET_STARTED is equal to the string "Get Started" <script setup> import { GET_STARTED } from '../../constants' import GreenBtn from '@/components/p ...

Node.js server is slow to shut down

I am facing an issue with my Node.js HTTP server. When I send a request and receive the response, attempting to close the server using server.close() takes more than 60 seconds. What could be causing this delay? Edit Currently, I am testing with Chrome&a ...

Prevent the default scroll event triggered by the mousewheel in certain situations. It is not possible to use preventDefault within a passive event

I have a div element with the onWheel attribute. By default, the browser interprets onWheel as scroll behavior. However, I want to prevent the browser's default mouse behavior under certain conditions. Unfortunately, I encountered an error that say ...

The mock-up functions flawlessly on my local machine, however, it is failing to run on the server with the JEST framework

Seeking assistance with unit testing using JEST framework for Node.js. Although the tests run successfully on my local machine, they fail to mock properly on both the server and my colleague's machine. After researching online, I came across suggestio ...

do not display entries with expired duration

update1: Unfortunately, even after testing in the sandbox, the result is still returning empty :( https://codesandbox.io/s/happy-https-u8lu2 After filtering my starsValues based on height and weight, I am able to get some results. However, I also n ...

Modifying subtotal values using PHP and JavaScript

I've been working on this code snippet to calculate my subtotal and determine the total payment. Can someone provide some assistance? $viewx = mysql_query("select distinct toorderid from ordercontainer where toordercategory='$ordercategory' ...

Is it possible to use the .focus() event on an entire form in JQuery? If so, how

Take a look at this HTML snippet: <form ....> <textarea>....</textarea <input .... /> </form> I'm trying to set up a help section that appears when the user focuses on any form element, and disappears when they lose ...

Add elements to an array with express, Node.js, and MongoDB

I'm currently learning about the MERN stack and I'm working on creating users with empty queues to store telephone numbers in E.164 format. My goal is to add and remove these numbers from the queue (type: Array) based on API requests. However, I ...

Using Github: How do you npm install a repository that has been forked into another repository?

Having trouble with the installation of a modified repository Pm2 fix, which is a fork of the original Pm2 original. I have a couple of queries: How do I use npm to install the pm2 fix? If I have already installed the pm2 fix using npm, can I still updat ...

A guide on generating customized HTML hyperlinks with specific URLs for each song utilizing Express.js and MySQL

As a beginner in Node & Express, this is my first project centered around developing a website for sharing free music. Currently, my main challenge involves creating individual HTML pages for each uploaded track with unique URLs. The database stores on ...

Exploring the power of QueryTask in ArcGIS JS API 3 for running multiple queries

When using QueryTask in ArcGIS JS Api 3, I encountered a challenge where I needed to execute multiple queries in one call. After referencing the documentation, I realized that this functionality was not directly supported. This is my current implementatio ...