如何使用Firebase Cloud Functions检测环境是开发环境还是生产环境?

时间:2018-11-07 07:57:00

标签: node.js firebase google-cloud-functions

如何使用Firebase Cloud Functions检测我的服务器环境是开发环境还是生产环境?

我需要这样的东西:

if(process.env.NODE_ENV === 'development'){

   //DO STUFF SPECIFIC TO DEV ENVIRONMENT

}
else if(process.env.NODE_ENV === 'production'){

   //DO STUFF SPECIFIC TO PRODUCTION ENVIRONMENT

}

3 个答案:

答案 0 :(得分:14)

process.env.FUNCTIONS_EMULATOR

process.env 的firebase函数项目上,有一个名为 FUNCTIONS_EMULATOR 的布尔变量,它指示进程是在模拟器上还是在服务器上运行。 / p>

这足以确定环境是开发环境还是生产环境。

process.env.FUNCTIONS_EMULATOR === true

obs:在某些环境中,变量可能是字符串'true'而不是布尔值 true

答案 1 :(得分:8)

您可以依靠process.env

截至2020年7月28日和package.json

"dependencies": {
    "firebase-admin": "^8.10.0",
    "firebase-functions": "^3.6.1"
},

如果您使用Firebase启动应用程序

firebase emulators:start

然后process.env将具有类似

的属性
"FUNCTIONS_EMULATOR": "true",
"FIRESTORE_EMULATOR_HOST": "0.0.0.0:5002",
"PUBSUB_EMULATOR_HOST": "localhost:8085"

如果您使用Firebase启动应用程序

firebase emulators:start --only functions

然后process.env将具有类似

的属性
"FUNCTIONS_EMULATOR": "true",

用例

基于process.env,您可以编写firebase.function来预填充您的Firestore模拟器(而非生产Firestore)!

代码示例

export const prepopulateFirestoreEmulator = functions.https.onRequest(
  (request, response) => {
    if (process.env.FUNCTIONS_EMULATOR && process.env.FIRESTORE_EMULATOR_HOST) {
      // TODO: prepopulate firestore emulator from 'yourproject/src/sample_data.json
      response.send('Prepopulated firestore with sample_data.json!');
    } else {
      response.send(
        "Do not populate production firestore with sample_data.json"
      );
    }
  }
);

答案 2 :(得分:2)

所有项目都是项目,除了您指定目的的方式。由于Cloud Functions无法了解开发和生产之间的区别,因此您需要检查项目的名称,因为这是环境中唯一发生变化的事情。使用automatically populated env vars中的process.env.GCLOUD_PROJECT

相关问题