【问题标题】:Know if express app is running as firebase cloud function知道 express 应用程序是否作为 firebase 云功能运行
【发布时间】:2019-04-21 00:19:47
【问题描述】:

我有一个快速应用程序,我想在我的机器上作为独立服务器在本地运行,但是,在将其部署到 firebase 云功能时,我需要将其设置为云功能。

有没有一种可靠的方法可以知道应用程序在哪个环境中运行而无需手动设置环境变量或最佳做法是什么?

例如:

if(isRunningInFirebase()){
  exports.myFun=functions.https.onRequest(app)
} else app.listen(3030)

【问题讨论】:

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


    【解决方案1】:

    Firebase 现在在运行模拟器时设置 FUNCTIONS_EMULATOR 环境变量:

    if (process.env.FUNCTIONS_EMULATOR === 'true') {
        functions are on localhost
    } else {
        functions are on Firebase
    }
    

    【讨论】:

      【解决方案2】:

      在本地或远程谷歌计算机上运行程序之前不必编辑程序可以节省大量时间。

      对象 process.env 在本地和在云中运行时都被断言。它有很大的不同,但我认为这是一个可靠、易于理解和使用的属性。

      这个独立代码说明它在哪里,并将变量端口设置为我在两种情况下都使用的常用数字。

      // Dan K The program wants to know, where am I ?
      'use strict'
      
      console.log( "program ID: " + "zincoNoDogs13" );
      
      // Make a message and set a port number for other uses depending on whether the
      // program wakes up on a local computer or in google cloud
      
      const functions = require( 'firebase-functions' );
      const express = require('express');
      const app = express();
      exports.api = functions.https.onRequest( app );
      
      var port;
      var imaThis = "local";
      let lookie = process.env.HOME;
      if( lookie == "/tmp" ) { imaThis = "cloud"; }
      
      if( imaThis == "local" ) {console.log( "I am on a local computer" ); port = 3000; }
      if( imaThis == "cloud" ) {console.log( "I am in the clouds man" ); port = 80; }
      
      console.log( "Port number is going to be: " + port );
      

      随便你选一个,或者好吧,反正我也选:

      程序 ID:zincoNoDogs13 我在云中人 端口号将是:80

      程序 ID:zincoNoDogs13 我在本地计算机上 端口号将是:3000

      【讨论】:

        【解决方案3】:

        我通过记录 process.env 做了一些探索

        当使用 firebase 函数在本地运行函数时:shell 或 firebase serve --only 函数有一堆本地机器类型节点变量。

        在 Firebase Cloud Functions 中运行已部署的函数时。有一个新的节点环境变量在本地运行时没有设置:

        NODE_ENV: 'production'
        

        所以要使用它:

        if (process.env.NODE_ENV === 'production') { 
            // running in production cloud environment 
        } else { 
            // running locally (shell or serve) 
        }
        

        【讨论】:

          【解决方案4】:

          在函数运行时和本地模拟函数中会自动填充一些环境变量,如 here 所述。例如,其中之一是 GCLOUD_PROJECT 变量,它设置为您的 Firebase 项目 ID。你可以让你的应用像这样检查它:

          if(process.env.GCLOUD_PROJECT) { 
              // running in Firebase environment 
          }
          else { 
              // running somewhere else 
          }
          

          【讨论】:

          猜你喜欢
          • 2019-10-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-05-15
          • 2021-01-13
          • 2017-09-28
          • 2020-05-01
          • 1970-01-01
          相关资源
          最近更新 更多