英文:
child_process spawn doesnt work if i run in the parent folder
问题
所以我正在使用child_process spawn来从nodejs和python中发送和接收数据。
以下是我的代码:
var py = spawn('python3', ['./python.py']),
var responseArray = []
py.stdin.write(JSON.stringify(sendData));
py.stdin.end();
py.stdout.on('data', function (data) {
responseArray = JSON.parse(data.toString())
});
py.stdout.on('end', function () {
console.log(responseArray)
});
所以在这段代码中,我展示了如果我直接像这样运行 node project.js,我可以接收到python发送给nodeJs的数据,但是如果我从父文件夹运行,就像这样 node folder/project.js,它会立即进入stdout,显示数据为空。
英文:
So I am working with child_process spawn for sending and receiving data from nodejs and python.
here is my code
var py = spawn('python3', ['./python.py']),
var responseArray = []
py.stdin.write(JSON.stringify(sendData));
py.stdin.end();
py.stdout.on('data', function (data) {
responseArray = JSON.parse(data.toString())
});
py.stdout.on('end', function () {
console.log(responseArray)
});
So in the code, I showed if I run directly like this node project.js, I receive the data the python sends to nodeJs, but if I run from the parent folder like this node folder/project.js, it will go immediately to stdout, showing the data empty
答案1
得分: 1
child_process.spawn
默认使用与 Node 进程相同的当前工作目录(cwd):
> 使用 cwd
来指定生成的进程的工作目录。如果未提供,默认继承当前工作目录。
因此,如果您从父文件夹调用 JS 脚本,您的当前工作目录将是该父文件夹,但您的 python.py
文件不在那里。
正如链接文档中所描述的,您可以使用 spawn
的第三个参数来指定选项,特别是应该使用的 cwd
:
spawn('python3', ['./python.py'], {
cwd: './folder' // 或更好的是绝对路径
})
...或者简单地修复到您的 Python 脚本的路径:
spawn('python3', ['./folder/python.py'])
英文:
child_process.spawn
uses by default the same current working directory (cwd) of the Node process:
> Use cwd
to specify the working directory from which the process is spawned. If not given, the default is to inherit the current working directory.
So if you invoke the JS script from a parent folder, your CWD is that parent folder, but your python.py
file is not there.
As described in the linked docs, you can use a 3rd argument to spawn
to specify options, in particular cwd
that should be used:
spawn('python3', ['./python.py'], {
cwd: './folder' // Or better: an absolute path
})
...or simply fix the path to your Python script:
spawn('python3', ['./folder/python.py'])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论