假设我们有一个包含以下内容的env.sh。
export SOME_VAL="abcd"我们想从一个JS (node.js)脚本bootstrap.js中获取这个shell脚本。
const childProcess = require('child_process');
const cmd = '. ' + pathToEnvScript;
childProcess.exec(cmd, (err, stdout, stderr) => {
if (err) console.error(err);
console.log(stdout);
})下面是我们调用bootstrap.js的方式。
echo $SOME_VAL # empty
node bootstrap.js
echo $SOME_VAL # empty为什么采购没有任何效果?如果我们从终端调用source env.sh,则源可以工作,但对node bootstrap.js不起作用。
发布于 2017-12-01 11:16:19
这至少有两个原因是不起作用的。source是一个Bash internal command,默认情况下,节点会派生/bin/sh。即使您告诉child_process.exec生成一个Bash shell:
child_process.exec("ls", { shell: "/bin/bash" }, (err, stdout) => ())
然后,将source'd变量添加到外壳进程的环境中,而不是node.js的环境中。
我不知道您的项目的具体需求是什么,但您最好的选择可能是打开node中的文件并解析其内容,以找到键/值对并以这种方式设置节点的环境。
https://stackoverflow.com/questions/47585290
复制相似问题