【问题标题】:Node How to share process.env between multiple runs?Node 如何在多个运行之间共享 process.env?
【发布时间】:2021-09-12 19:21:54
【问题描述】:

考虑以下内容。

node file1.js && react-scripts start

我正在尝试对 file1.js 中的 GCP Secret Manager 进行 API 调用。收到请求后,我想将它们设置为process.env下的环境变量。之后,我想在前端访问它们。浏览器无法在没有 OAuth 的情况下调用该 Secret Manager。有什么方法可以在这两个脚本之间共享 process.env 吗?

文件1代码

const {SecretManagerServiceClient} =  require('@google-cloud/secret-manager');

// Instantiates a client
const client = new SecretManagerServiceClient();

const firebaseKeysResourceId = 'URL'
const  getFireBaseKeys=async()=> {
  const [version] = await client.accessSecretVersion({
    name: firebaseKeysResourceId,
  });

  // Extract the payload as a string.
  const payload = JSON.parse(version?.payload?.data?.toString() || '');
  process.env.TEST= payload.TEST
  return payload
}

getFireBaseKeys()

【问题讨论】:

  • 不可能像这样通过 shell 直接共享数据。你可以: 1. 让file1.js 打印可导出的值,然后你可以sourceeval 它像source $(node file1.js); react-scripts start 2. 让file1.js 写入磁盘并从磁盘源。 3. 在它自己的子进程中制作file1.js exec react-scripts,它可以在其中生成环境。
  • 环境变量可以向下填充但不能向上填充。正如sethvargo 所说,您最好的选择可能是从file1.js 生成react-scripts,默认情况下,子进程将继承父进程的环境。另一种选择是让file1.js only 打印 OAUTH 密钥并像这样运行它以传入名为 OAUTH 的环境变量:OAUTH=$(node file1.js) ./react-scripts start
  • @leitning 你能扩展更多关于子进程的内容吗?由于文件是异步的,我认为您的第二个选项不会起作用。添加代码。
  • 生成进程始终是异步的,第二个选项将起作用,因为 bash 将等待$(...) 内部的进程完成后再继续。 child_process.spawn 上的文档在这里 nodejs.org/docs/latest-v14.x/api/…
  • @leitning 在第二个选项中,会有 5-6 个 env 变量。我需要单独设置它们吗?

标签: node.js google-cloud-platform package.json google-secret-manager


【解决方案1】:

扩展我的评论

方法 1 - 有点整洁但不必要

假设你在环境中有这些你想要的变量:

const passAlong = {
  FOO: 'bar',
  OAUTH: 'easy-crack',
  N: 'eat'
}

然后在 file1.js 的末尾你会这样做

console.log(JSON.stringify(passAlong));

注意你不能在file1.js中打印任何东西

然后你会这样调用你的脚本

PASSALONG=$(node file1.js) react-script start

并且在 react-script 的开头,您将执行此操作以将传递的变量填充到环境中。

const passAlong = JSON.parse(process.env.PASSALONG);
Object.assign(process.env,passAlong);

方法 2 - 我会怎么做

使用 spawn 方法只需要在 file1.js 中设置你喜欢的 process.env,然后在 file1.js 的末尾添加类似的内容

// somewhere along the way
process.env.FOO = 'bar';
process.env.OAUTH = 'easy-crack';
process.env.N = 'eat';

// at the end of the script
require('child_process').spawnSync(
  'node', // Calling a node script is really calling node
  [       //   with the script path as the first argument
   '/path/to/react-script', // Using relative path will be relative
   'start'                  //   to where you call this from
  ],                        
  { stdio: 'inherit' }
);

【讨论】:

  • 在方法 1 中,它说。 PASSALONG 未被识别为内部或外部命令。
  • Bash 不允许在 var 赋值中使用空格。确保它是 PASSALONG=$... 而不是 PASSALONG = $...
  • 是的,就是这样。问题似乎与 $() 语法有关。
  • 您使用的是什么操作系统?如果它是一个 linux 发行版,你会从 echo $SHELL 得到什么
  • 我在 Windows 上。
猜你喜欢
  • 1970-01-01
  • 2014-03-29
  • 1970-01-01
  • 1970-01-01
  • 2020-07-31
  • 2012-07-22
  • 2014-07-10
  • 1970-01-01
  • 2018-03-30
相关资源
最近更新 更多