Search code examples
node.jspython-3.xbase64spawn

Node.js: Passing image as base64 to python with spawn


I'm trying to pass an image as base64 to python for processing using spawn like so:

return new Promise(function(resolve, reject) {
      const pythonProcess = spawn('python',["./python.py", imageDataURI]);
      pythonProcess.stdout.on('data', (response) => {
        resolve(response);
      });
    });

But I'm getting error: Error: spawn E2BIG I guess it's too big to pass like this, any alternative ways to pass it to spawn?

Seems related:

Node / child_process throwing E2BIG


Solution

  • Thanks to ottomeister's answer I did it like this:

    In Node:

    const pythonProcess = spawn('python',["script.py"]);
    
    pythonProcess.stdin.write(data);
    pythonProcess.stdin.end();
    pythonProcess.stdout.on('data', (result) => {
        handleResult(result);
    });
    

    In python:

    import fileinput
    
    for line in fileinput.input():
        input +=line
    
    # Process input
    
    sys.stdout.write(result)
    sys.stdout.flush()