问题
Anybody figure out syntax or a pattern yet for detecting hosting environment using Meteor.js? I've got Heroku buildpacks working, and have a dev/production environment, but I'm kind of drawing a blank on how to have my app detect which environment it's running in.
Is there a way to have node.js detect which port it's running on? I was hoping there might be something low-level like app.address().port, but that doesn't seem to work...
Edit: This is the solution that worked for me. Note that the following needs to be run on the server, so it needs to be included in server\server.js, or a similar file.
if (Meteor.is_server) {
Meteor.startup(function () {
// we want to be able to inspect the root_url, so we know which environment we're in
console.log(JSON.stringify(process.env.ROOT_URL));
// in case we want to inspect other process environment variables
//console.log(JSON.stringify(process.env));
});
}
Also created the following:
Meteor.methods({
getEnvironment: function(){
if(process.env.ROOT_URL == "http://localhost:3000"){
return "development";
}else{
return "staging";
}
}
});
Which allows for the following on client side:
Meteor.call("getEnvironment", function (result) {
console.log("Your application is running in the " + result + "environment.");
});
Thanks Rahul!
回答1:
You can inspect the process.env variable on the server to find information about the current environment, including the port:
{ TERM_PROGRAM: 'Apple_Terminal',
TERM: 'xterm-256color',
SHELL: '/bin/bash',
TMPDIR: '/var/folders/y_/212wz0cx5vs20yd7y2psnh7m0000gp/T/',
Apple_PubSub_Socket_Render: '/tmp/launch-hch25f/Render',
TERM_PROGRAM_VERSION: '309',
OLDPWD: '/usr/local/meteor/bin',
TERM_SESSION_ID: '3FE307A0-B8FC-41AD-B1EB-FCFA0B8B25D1',
USER: 'Rahul',
COMMAND_MODE: 'unix2003',
SSH_AUTH_SOCK: '/tmp/launch-gFCBXS/Listeners',
__CF_USER_TEXT_ENCODING: '0x1F6:0:0',
Apple_Ubiquity_Message: '/tmp/launch-QAWKHL/Apple_Ubiquity_Message',
PATH: '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
PWD: '/Users/Rahul/Documents/Sites/test',
NODE_PATH: '/usr/local/meteor/lib/node_modules',
SHLVL: '1',
HOME: '/Users/Rahul',
LOGNAME: 'Rahul',
LC_CTYPE: 'UTF-8',
SECURITYSESSIONID: '186a4',
PORT: '3001',
MONGO_URL: 'mongodb://127.0.0.1:3002/meteor',
ROOT_URL: 'http://localhost:3000' }
回答2:
there is a direct Meteor function:
Meteor.isDevelopment
see: https://docs.meteor.com/api/core.html#Meteor-isDevelopment
and for production:
Meteor.isProduction
both return a boolean
回答3:
I used a variation of the above with the NODE_ENV variable. See here for more info:
http://meteorpedia.com/read/Environment_Variables#Checking%20the%20value%20of%20an%20Environment%20Variable
if Meteor.isServer
Meteor.methods
'getEnvironment': -> process.env.NODE_ENV
Meteor.call 'getEnvironment', (err, result) ->
if result == 'development'
console.log('In dev env')
来源:https://stackoverflow.com/questions/14184643/detecting-environment-with-meteor-js