简体   繁体   中英

child_process in NodeJS not having an error when it's supposed to

I use nodeJS and express as a server and use child_process.spawn to run a python script. After running the script, I get the result and send it as a json response.

When I get correct post response, the server responses the right response. When I post wrong parameters, the servers responses with the error message (as expected)

But when I post the wrong parameters after the correct parameter post, it gives the previous post's response and I don't know why. Maybe this is because of the spawn and should I use exec?

I want to know why this is happening. Let me know if you need more details on this.

const { json } = require('body-parser')
const express = require('express')
const { setTimeout } = require('timers')
const router = express.Router()
let dataToSend;



router.post('/',  (req, res) => {

    // console.log(req.body)

    let resol = req.body.Resolution;
    let url1 = req.body.FirstImageURI;
    let url2 = req.body.SecondImageURI;
    let roi = req.body.DetectionArea;
    let sens = req.body.Threshold;
    if (isNaN(sens)) sens = "50";

    console.log("start ai model");
    console.log(`params : ${url1} ${url2} ${roi} ${sens}`);
    const spawn = require("child_process").spawn;
    const pythonProcess = spawn('python', ["img_diff.py", url1, url2, roi, sens]);


    pythonProcess.stdout.on('data', function (data) {
        console.log('Pipe data from python script ...');
        dataToSend = data.toString();
        console.log(`data in stdout : ${dataToSend}`)
    });


    // in close event we are sure that stream from child process is closed
    pythonProcess.on('close', (code) => {
        try {
            jsonObject = {}
            console.log(`child process close all stdio with code ${code}`);
            // format json
            dtList = dataToSend.split('\n');
            ssim = Number(dtList[0].split(":")[1]);
            detected = "UnDetected"
            console.log(dtList[1])
            let addInfo = dtList[1].trim().slice(1, -1)
            addInfo = JSON.parse("[" + addInfo + "]");

            jsonObject.AdditionalInfo = []

            for (let i = 0; i < addInfo.length; i++) {
                let thisObject = {}
                thisObject.DetectedRegion = []
                for (let j = 0; j < addInfo[i].length; j++) {
                    coordObject = {}
                    coordObject.XCoord = addInfo[i][j][0]
                    coordObject.YCoord = addInfo[i][j][1]
                    thisObject.DetectedRegion.push(coordObject)
                }
                jsonObject.AdditionalInfo.push(thisObject)
            }

            if (jsonObject.AdditionalInfo.length > 0) {
                detected = "Detected"
            }
            jsonObject.Result = detected
            console.log(detected)
            res.json(jsonObject)
        } catch (e) {
            console.log(`error -> ${e}`)
            jsonObject.AdditionalInfo = [];
            let thisObject = {};
            thisObject.DetectedRegion = [];
            jsonObject.AdditionalInfo.push(thisObject);
            jsonObject.detected = "UnDetected";
            res.json(jsonObject);
        } 
    });

})



module.exports = router

Still don't know why this happens, but my guess is that as the process crashes, Node just gives a response from the previous successful memory.

Will come back and update if I have a better answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM