Search code examples
pythonnode.jschild-process

How can I transfer data from NodeJS to Python script


I have to use Python script in my NodeJS project, but I don't quite understand how to send data from Node to Python. In the Internet I've found information about child_process. So, I want to send an object and then get message that it has been proceed.

NodeJS:

const {spawn} = require('child_process');
const process = spawn('python3', ['process.py']);

async function start() { 
  let data = [1,2,3,4,5];
  process.stdin.write(JSON.stringify(data));
  process.stdin.end();
}

Python:

import sys, json, numpy as np
def read_in():
    lines = sys.stdin.readlines()
    return json.loads(lines[0])

def main():
    lines = read_in() 
    print (lines)

if __name__ == '__main__': 
    main()

Solution

  • Pass it in the array argument like this:

    const process = spawn('python3', ['process.py', var1, var2]);