3

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

K41F4r
  • 1,443
  • 1
  • 16
  • 36
  • 1
    Change the python script to read the image data from its standard input stream `sys.stdin`. Change the node.js script to write the image data to the Python process by calling `pythonProcess.stdin.write()` followed by `pythonProcess.stdin.end()` to indicate that all of the data has been written. – ottomeister Apr 22 '19 at 23:07
  • Yup, that worked, thanks. In python, read it with `for line in fileinput.input()` (and wrote back out with `sys.stdout.write()` and `sys.stdout.flush()`) – K41F4r Apr 23 '19 at 09:23
  • @ottomeister is there an alternative to end() in case I want to reuse the stream? – K41F4r Apr 24 '19 at 15:15

1 Answers1

1

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()
lxknvlk
  • 2,744
  • 1
  • 27
  • 32
K41F4r
  • 1,443
  • 1
  • 16
  • 36
  • I don't get the purpose, you are sending buffer to python from nodejs, & then writting it back to nodejs ? In my case I want to send image buffer to python & do some image processing, without sending it back to nodejs – Muhammad Uzair Nov 12 '22 at 12:54