简体   繁体   中英

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

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)

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])

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