Node.js child_process spawn All In One
Node.js 多线程
// const { spawn } = require('child_process');
const { spawn } = require('node:child_process');
// $ ls -al /usr 等价于
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}`);
});
https://nodejs.org/api/child_process.html
How to run Python script code in Node.js?
如何在 Node.js 中运行 Python 脚本代码?
// const { spawn } = require('child_process');
const { spawn } = require('node:child_process');
// async API
async function generateJsonFile(req, res) {
// console.log(1)
let pyData;
// python3 ./py-script.py Node.js ✅
const py = spawn('python3', ['./py-script.py', 'Node.js']);
// py3 ./py-script.py Node.js ❌ py3 alias not work ❌
// const py = spawn('py3', ['./py-script.py', 'Node.js']);
// const py = spawn('py3', ['./py-script.py', 'Node.js'], {
// stdio: 'inherit',
// // shell: true,
// });
py.stdout.on('data', data => {
console.log(`✅buffer =`, data);
// DataView
pyData = data.toString();
console.log('✅Data received from python script =', `❓` + pyData + `❓`);
});
py.stderr.on('data', (data) => {
console.error(`❌stderr: ${data}`);
});
py.on('close', (code) => {
console.log('
标签:Node,spawn,process,py,js,sys,flush,data
From: https://www.cnblogs.com/xgqfrms/p/17700529.html