0

I am building a small express app that basically just reads the files from a directory renames them and then zips the files , now the reading and renaming part of the files is done synchronously , the ziping part is done asynchronously and then my app renders another view, so my logic is something like below:

/*
    // file read and renaming code here
 */

// Zip files code below:

try {
        let files_converted = fs.readdirSync(OUTPUT_DIRECTORY);
        let file_converstion_async_array = [];

        files_converted.forEach( (e , i) => {
            file_converstion_async_array.push( () => zip_Directory( `${OUTPUT_DIRECTORY}/${e}` ,  `${OUTPUT_DIRECTORY}/${e}.zip` ) );
        });

        console.log('Files are being zipped...');        

        file_converstion_async_array.reduce( ( promise_chain , current_promise ) => {

            return promise_chain.then( p_results => {
                return current_promise().then( c_result => {
                    // console.log('ZIPPED');
                });
            });

        } , Promise.resolve([]) ).then( () => {
            console.log('All Files have been zipped...');
        });

    } catch (err) {
        console.error(err);
    }

  // Finally render a new view 

    res.render("finish", {
       name: req.body.outputPath
    });

Now what happens is the syncronious code run and then the new view is rendered and then the asycronious code continues running in the background. What i would like to do is once the asyncronious code is executed for my view to be updated with a new message , how can i do this without showing another new view(which i am not sure is possible because i tried this and i beleive you can use res.render only once .) , so after all the promises have been executed , i would really like to go ahead and render a new message in the view. How do i go about doing that ?

Alexander Solonik
  • 9,838
  • 18
  • 76
  • 174

1 Answers1

1

You are correct about not being able to send multiple res.render. In standard HTTP, a client expects to receive a fixed content length and you won't be able to change it later while sending it.

Usually, when you want to achieve something like this, have your client send a second request, which blocks until the server really is done with its async actions. You could use a websocket connection or something very sophisticated, but here is a small example leveraging express' ability to dynamically use routes:

const express = require("express");
const app = express();

let jobs = {};

app.get("/jobs/:number.js", (req, res) => {
  const jobNr = req.params.number;
  const job = jobs[jobNr];
  if (!job) {
    console.log("no job found!");
    return res.sendStatus(404);
  }

  job
    .then(result => res.send(`document.getElementById("result-${jobNr}").innerHTML = "job ${jobNr} is done with ${result}";`))
    .catch(err => res.sendStatus(500))
    .then(() => {
      // finally clean up, as some client requested this resource
      jobs[jobNr] = null;
    });
});

app.get("/", (req, res) => {

  // set up a job with whatever is necessary to do
  const jobNr1 = Math.floor(Math.random() * 10000000);
  const job = new Promise(resolve => setTimeout(() => resolve("a result!"), Math.random() * 5000 + 2000));
  jobs[jobNr1] = job;

  // set up a second job with whatever is necessary to do
  const jobNr2 = Math.floor(Math.random() * 10000000);
  const job2 = new Promise(resolve => setTimeout(() => resolve("another result!"), Math.random() * 5000 + 2000));
  jobs[jobNr2] = job2;

  res.send(`<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>test</title>
</head>
<body>
  <div id="result-${jobNr1}">job ${jobNr1} running...</div>
  <div id="result-${jobNr2}">job ${jobNr2} running...</div>
  <script async src="/jobs/${jobNr1}.js"></script>
  <script async src="/jobs/${jobNr2}.js"></script>
</body>
</html>
`);
});

app.listen(8080);
Narigo
  • 2,979
  • 3
  • 20
  • 31