繁体   English   中英

了解 express 应用程序是否作为 Firebase 云功能运行

[英]Know if express app is running as firebase cloud function

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

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

例如:

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

有一些环境变量会自动填充到函数运行时和本地模拟函数中,如此处所述 例如,其中之一是GCLOUD_PROJECT变量,它设置为您的 Firebase 项目 ID。 您可以让您的应用程序检查它,如下所示:

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

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

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

我通过记录 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) 
}

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

对象 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:zinoNoDogs13 我在云端 man 端口号为:80

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM