我最近偶然发现了一个错误,即exec()
函数启动的进程失败,因为它找不到环境变量。
我在SO上找到了解决方案,但现在我有一个问题。
exec()
从child_process
加载中运行哪个 bash 环境?(不确定这个问题是否写得很好,所以我会解释更多)。
// app.js
const {exec} = require('child_process');
const http = require('http');
// Create an instance of the http server to handle HTTP requests
let app = http.createServer((req, res) => {
// Set a response type of plain text for the response
res.writeHead(200, {'Content-Type': 'text/plain'});
exec('echo $PATH > foo.txt'); // <<<<<<<<
// Send back a response and end the connection
res.end('Hello World!n');
});
// Start the server on port 3000
app.listen(3000, '127.0.0.1');
console.log('Node server running on port 3000');
如果我运行上面的代码,我会得到包含$PATH
内容的foo.txt
文件,这意味着exec()
生成的 shell 环境可以找到环境变量。
但是,如果我尝试将$PATH
更改为$MY_OWN_VARIABLE
即使我在.bashrc
中添加了行export MY_OWN_VARIABLE="foo bar baz"
,它也找不到它。
(出于测试目的,我以 root 身份在 VM 中工作,所以我更改了根 bashrc)。
似乎exec()
在生成外壳时没有使用 bashrc,但它仍然会找到一些变量,例如$PATH
但不是我定义的变量,我不知道为什么。
这只是纯粹的好奇心,上面链接的解决方案解决了我的问题,但它仍然困扰着我。
注意:我不熟悉节点,可能也不熟悉如何创建 bash shell。
尝试重新启动根会话并检查是否使用echo $MY_OWN_VARIABLE
设置了$MY_OWN_VARIABLE
。可能只需要重新启动会话。