Showing the loading page until I get a response from the server

Viewed 34

I am running a python script at my server on the data I gave to it by using a form. The script takes a 6-8 sec running time and after running the script, I render a different page. What I want is that a loading page appears while the script is running at backend.

My code is:

    var express = require("express"),
        router = express.Router();
    var Place = require("../models/place"),
        Comment = require("../models/comment");
    var middleware = require("../middleware"),
        multer = require("multer"),
        path =  require("path"),
        {spawn} = require("child_process"),
        fs = require("fs");


    function runScript(pathToImage){
        return spawn('python', [
          "-u", 
          path.join(__dirname + "/../", 'script.py'),
          pathToImage, 
        ]);
    }

    //CREATE Route

    //route to get the form
    router.get("/new", middleware.isLoggedIn, function(req, res){
        res.render("places/new");
    });
    //post route
    router.post("/", middleware.isLoggedIn, uploadDir.single("image"), function(req, res){
        var name = req.body.name;
        var imgurl = "/uploads/images/" + req.file.filename;
        var description = req.body.description;
        var author = {
            id: req.user._id,
            username: req.user.username
        };
        let garbageVal;


        //running my python script

        const subprocess = runScript("uploads/images/" + req.file.filename);
        // print output of script
        subprocess.stdout.on('data', (data) => {
            garbageVal = data.toString();
        });
        subprocess.on('close', () => {
            if(garbageVal === "Garbage found\n"){
                var newPlace = {name:name, image:imgurl, description:description, author:author, garbageVal:garbageVal};
                //Create a new place and save to DB
                Place.create(newPlace, function(err, newlyCreated){
                    if(err){
                        console.log("DB inserting error");
                    }
                    else{
                        res.redirect("/places");
                    }
                });
            }
            else{
                req.flash("error", "No garbage found in the uploaded image.");
                fs.unlink("uploads/images/" + req.file.filename, (err) => {
                    if (err){
                        console.log(err);
                        return res.redirect("back");
                    }
                    console.log("Image deleted from server");
                    res.redirect("/places");
                });
            }         
        });       
    });

I tried by adding a loader div and setting its display property to none when my body loads on a page but this has no effect as when I am running my python script there is no response from the server.

0 Answers
Related