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

Horizontal scroll box content is being truncated

I've been trying to insert code into my HTML using JavaScript, but I'm facing a problem where the code is getting truncated or cut off. Here's the snippet of code causing the issue: function feedbackDiv(feedback_id, feedback_title, feedb ...

Issues with establishing a connection to socket.io through firebase functions and express

I've been attempting to establish a socket.io connection with firebase hosting/functions, but I've encountered some issues along the way. Initially, it seemed like a CORS problem (which might still be the case), but now I'm completely lost a ...

Passing JSON data dynamically to create a chart with chartjs

I have also developed this project on codesandbox: https://codesandbox.io/s/bar-graph-9nr8u?file=/src/App.js:2394-3036 I possess JSON data and a Pie graph with labels including car, bikes, motor, and trucks. My goal is to display the total number of users ...

Designing a node module that allows access to various extended classes written in separate CoffeeScript files

I am interested in creating a single-node library that consists of multiple classes, each written in coffee-script and stored in separate files within node_modules/mymodule/src directory. To illustrate, consider the following file structure: File 1: clas ...

What is the method for assigning a value to a variable in xhr.setRequestHeader?

I'm working on setting a value to the variable in xhr.setRequestHeader(Authentication, "Bearer" + parameter); with xmlhttprequest. Can you provide guidance on how to effectively pass a value to the variable within xhr.setRequestHeader? ...

Instead of pushing multiple items, focus on pushing only one item at a time

I've encountered an issue while attempting to add a new item to my favlist. Using a for loop, I check if the item already exists in the favlist. However, instead of adding the new item only once, it ends up being added multiple times. What would be ...

Access the JavaScript variable in a webview and store it in an Android variable

I have been attempting to retrieve a variable from a webview, but I am only able to make modifications like this: browser.loadUrl("javascript:var x = document.getElementById('login').value = 'something';"); However, I need to be able ...

Tips for avoiding infinite re-render loop when updating state in React/Next.js

I currently have a unique Next.js application that showcases randomly selected YouTube videos. The state within the app is structured as follows (managed by Redux): const state = { entities: { videos: { 'vidId1': { ...

The underscore convention for defining members in Typescript allows for clear and concise

Let's talk about a class called Email class Email { private _from: string; private _to: Array<string>; private _subject: string; } When an email object is created, it will look something like this: { _from:'', _to:'&apo ...

React components are graced with a clear icon that is visible on every element

I'm attempting to show a remove icon on a grid display when the user hovers over it with their mouse. this.state = { action: [], } <div> {this.state.action.map((value, index) => { return ( <div key={index} onMouseEnte ...

React Native vector icons display enigmatic symbols

I recently installed react-native-vector, but I'm seeing strange symbols when using it. Can anyone provide guidance on how to properly utilize this library? Platform: Android import React from 'react'; import {View, Text, StyleSheet} from & ...

Accessing secure managed Redis using Node.js authentication credentials

Upon further reflection, the question that arises is how to connect to digitalocean's managed redis with node-redis using tls. Although I can establish a connection with the redisinsight GUI client using a username and password without any issues, I ...

Convert angular-tree-component JSON into a suitable format and dynamically generate checkboxes or radio buttons

Currently, I am using the angular-tree-component for my treeview implementation. You can find more details about it in this reference link. The array structure I am working with is as follows: nodes = [ { id: 1, name: 'root1', ...

Engaging with Grunt extensions

I'm facing an issue with my gruntfile. Here is the configuration: module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), htmlhint: { build: { optio ...

How can I implement a progress bar that mimics an exchange platform behind data-table components? [Using Vue and Vuetify]

I am working on a cryptocurrency exchange book simulator and I am trying to implement a progress bar that will be displayed behind the values in a table. https://i.stack.imgur.com/9gVsY.png This is the template for my data-table: < ...

Retrieve the source code of a webpage by accessing its URL with JavaScript through the use of JSONP

To extract the source code from a URL web page using JSONP, you can use the following code snippet: <script type="text/javascript"> var your_url = ''; $(document).ready(function(){ jQuery.ajax = (function(_ajax){ var protocol = location. ...

What is the best way to modify the Xtype attribute based on whether the device is running on Android or iOS

I am currently working on a project using Extjs6.0.2, but I have encountered an issue with creating the xtype: 'namefield'. It seems that this type of xtype is supported on Android devices but not on iOS devices. Despite this challenge, I am dete ...

Tips for eliminating repeated values in a textbox

<script> $("#filter").on("shown.bs.popover",function(){ $(".popover-content input[type=checkbox]").on("click",function(){ if(this.checked) { this.setAttribute("checked","checked"); } else { ...

Save the content of a string object into an array

I am currently implementing an array sorting functionality using the MVC approach. The array called "array" is used to store values provided at runtime. Within the view, there is a textbox and a button for user input of integer values. Upon clicking the bu ...

Enable search functionality for jQuery Select2 values that have been formatted by a formatter function

Trying to use a formatter with select2 for better alignment of code and description elements, but the plugin seems to be searching based only on the description rather than the entire text. This may be because it's only looking at the original <opt ...