node child_process spawn code example
Example 1: node spawn
const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
ls.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
});
ls.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
Example 2: child process spawn python node js
const path = require('path')
const {spawn} = require('child_process')
/**
* Run python myscript, pass in `-u` to not buffer console output
* @return {ChildProcess}
*/
function runScript(){
return spawn('python', [
"-u",
path.join(__dirname, 'myscript.py'),
"--foo", "some value for foo",
]);
}
const subprocess = runScript()
// print output of script
subprocess.stdout.on('data', (data) => {
console.log(`data:${data}`);
});
subprocess.stderr.on('data', (data) => {
console.log(`error:${data}`);
});
subprocess.stderr.on('close', () => {
console.log("Closed");
});
Example 3: how to return when child process is complete in node js
var child = require('child_process').exec('python celulas.py')
child.stdout.pipe(process.stdout)
child.on('exit', function() {
process.exit()
})
Example 4: child process spawn python node js
import sys, getopt, time
def main(argv):
argument = ''
usage = 'usage: myscript.py -f <sometext>'
try:
opts, args = getopt.getopt(argv,"hf:",["foo="])
except getopt.GetoptError:
print(usage)
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print(usage)
sys.exit()
elif opt in ("-f", "--foo"):
argument = arg
print("Start : %s" % time.ctime())
time.sleep( 2 )
print('Foo is')
time.sleep( 2 )
print(argument)
print("End : %s" % time.ctime())
if __name__ == "__main__":
main(sys.argv[1:])
Example 5: how to return when child process is complete in node js
var execSync = require('exec-sync');
var user = execSync('python celulas.py');