Home > Blockchain >  How to pass variable in child_process and access the variable in child process in nodejs
How to pass variable in child_process and access the variable in child process in nodejs

Time:07-03

Code for parent.js

const {spawn} = require("child_process");

const encodeImage = (req,res)=>{
    try {
        const path = req.file.path;
        let dataToSend;

        const python = spawn('python', ['controllers/script.py']);
        
        python.stdout.on('data', function (data) {
            dataToSend = data.toString();
        });
        python.on('close', (code) => {
            res.send(dataToSend)
        });
    } catch (error) {
        console.log(error);
    }
}
    

Code for child.py - Want to pass path variable as argument (for opencv function)

import cv2 as cv

img = cv.imread(path)

CodePudding user response:

The easiest approach would probably be to pass it as a command-line argument:

In the JavaScript code:

const python = spawn('python', ['controllers/script.py', path]);

In the Python code:

import sys
import cv2 as cv

img = cv.imread(sys.args[1])
  • Related