假设我们有一个包含以下内容的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 14:21:39
鉴于此,
子进程不能修改它的父环境(除非你破解了你的外壳)
你能做的最多就是
make nodejs告诉您的shell如何更新其环境,就像它自己编写脚本一样。
我假设你只对变量而不是函数感兴趣。
这就是你的解决方案。
bootstrap.js
const childProcess = require('child_process');
const script = process.argv[2];
childProcess.exec("env > ./1.txt; . ./"+script+" >/dev/null 2>&1; env > ./2.txt; diff 1.txt 2.txt | grep '^>'", (err, stdout, stderr) => {
stdout.split('\n').forEach((line) => console.log(line.substr(2)));
})以及你应该如何称呼它:
echo $SOME_VAL # empty
eval `node bootstrap.js ./file.sh`
echo $SOME_VAL # abcd发布于 2017-12-01 10:33:43
使用export的childProcess.exec(command) spawns a shell then executes the command within that shell.使变量可用于shell的子进程,但不能用于其父进程。Node和从中调用Node的shell永远看不到该变量。
发布于 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
复制相似问题