Dart Node.js settings.env equivalent - dart

What is the equivalent statement in Dart for the Node Express code:
app.settings.env
as in
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
I've looked at ArgResults but I'm not clear as to how to use it.

From the express documentation:
env - Environment mode, defaults to process.env.NODE_ENV or "development"
The problem boils down to accessing environment variables, which has been addressed here: Access to user environment variable
import 'dart:io';
main() {
String env;
if (Platform.environment.containsKey("DART_ENV")) {
env = Platform.environment["DART_ENV"];
} else {
env = "development";
}
}
ArgResults just parses command-line arguments, which is likely not what you want. Use ArgParser instead.

Related

Nuxt 3 environment variables for static site [duplicate]

I have .env file in the project root, and in my nuxt config I am using variables to configure ReCaptcha like this:
import dotenv from 'dotenv'
dotenv.config()
export default {
modules: [
['#nuxtjs/recaptcha', {
siteKey: process.env.RECAPTCHA_SITE_KEY,
version: 3,
size: 'compact'
}],
]
}
and in .env like this:
RECAPTCHA_SITE_KEY=6L....
but the application always failed with console log error:
ReCaptcha error: No key provided
When I hard-code ReCaptcha key directly like that: siteKey: 6L.... app start working, so I guess the problem is with reading .env props in nuxt.config
do you have any idea how to fix it?
EDIT:
I tried update my nuxt.config by #kissu recommendation and by example which I found here: https://www.npmjs.com/package/#nuxtjs/recaptcha
so there is new nuxt.config which also not working:
export default {
modules: [
'#nuxtjs/recaptcha',
],
publicRuntimeConfig: {
recaptcha: {
siteKey: process.env.RECAPTCHA_SITE_KEY,
version: 3,
size: 'compact'
}
}
}
If your Nuxt version is 2.13 or above, you don't need to use #nuxtjs/dotenv or anything alike because it is already backed into the framework.
To use some variables, you need to have an .env file at the root of your project. This one should be ignored by git. You can then input some keys there like
PUBLIC_VARIABLE="https://my-cool-website.com"
PRIVATE_TOKEN="1234qwer"
In your nuxt.config.js, you have to input those into 2 objects, depending of your use case, either publicRuntimeConfig or privateRuntimeConfig:
export default {
publicRuntimeConfig: {
myPublicVariable: process.env.PUBLIC_VARIABLE,
},
privateRuntimeConfig: {
myPrivateToken: process.env.PRIVATE_TOKEN
}
}
Differences: publicRuntimeConfig can basically be used anywhere, while privateRuntimeConfig can only be used during SSR (a key can only stay private if not shipped to the browser).
A popular use case for the privateRuntimeConfig is to use it for nuxtServerInit or during the build process (either yarn build or yarn generate) to populate the app with headless CMS' API calls.
More info can be found on this blog post: https://nuxtjs.org/blog/moving-from-nuxtjs-dotenv-to-runtime-config/
Then, you will be able to access it into any .vue file directly with
this.$config.myPublicVariable
You access it into Nuxt's /plugins too, with this syntax
export default ({ $axios, $config: { myPublicVariable } }) => {
$axios.defaults.baseURL = myPublicVariable
}
If you need this variable for a Nuxt module or in any key in your nuxt.config.js file, write it directly with
process.env.PRIVATE_TOKEN
Sometimes, the syntax may differ a bit, in this case refer to your Nuxt module documentation.
// for #nuxtjs/gtm
publicRuntimeConfig: {
gtm: {
id: process.env.GOOGLE_TAG_MANAGER_ID
}
},
PS: if you do use target: server (default value), you can yarn build and yarn start to deploy your app to production. Then, change any environment variables that you'd like and yarn start again. There will be no need for a rebuild. Hence the name RuntimeConfig!
Nuxt3 update
As mentioned here and in the docs, you can use the following for Nuxt3
nuxt.config.js
import { defineNuxtConfig } from 'nuxt3'
export default defineNuxtConfig({
runtimeConfig: {
public: {
secret: process.env.SECRET,
}
}
}
In any component
<script setup lang="ts">
const config = useRuntimeConfig()
config.secret
</script>
In a composable like /composables/test.js as shown in this comment
export default () => {
const config = useRuntimeConfig()
console.log(config.secret)
}
Here is the official doc for that part.
You can also use the env property with Nuxt
nuxt.config.js:
export default {
// Environment variables
env: {
myVariable: process.env.NUXT_ENV_MY_VAR
},
...
}
Then in your plugin:
const myVar = process.env.myVariable
It's very easy. Providing you an example with axios/nuxt
Define your variable in the .env file:
baseUrl=http://localhost:1337
Add the variable in the nuxt.config.js in an env-object (and use it in the axios config):
export default {env: {baseUrl: process.env.baseUrl},axios: {baseURL: process.env.baseUrl},}
Use the env variable in any file like so:
console.log(process.env.baseUrl)
Note that console.log(process.env) will output {} but console.log(process.env.baseUrl) will still output your value!
For nuxt3 rc11, in nuxt.conf.ts file:
export default defineNuxtConfig({
runtimeConfig: {
public: {
locale: {
defaultLocale: process.env.NUXT_I18N_LOCALE,
fallbackLocale: process.env.NUXT_I18N_FALLBACK_LOCALE,
}
}
},
...
and in .env file:
NUXT_I18N_LOCALE=tr
NUXT_I18N_FALLBACK_LOCALE=en
public: is very important otherwise it cannot read it and gives undefined error.
For v3 there is a precise description in the official docs
You define a runtimeConfig entry in your nuxt.config.[ts,js] which works as initial / default value:
export default defineNuxtConfig({
runtimeConfig: {
recaptchaSiteKey: 'default value' // This key is "private" and will only be available within server-side
}
}
You can also use env vars to init the runtimeConfig but its written static after build.
But you can override the value at runtime by using the following env var:
NUXT_RECAPTCHA_SITE_KEY=SOMETHING DYNAMIC
If you need to use the config on client-side, you need to use the public property.
export default defineNuxtConfig({
runtimeConfig: {
public: {
recaptchaSiteKey: 'default value' // will be also exposed to the client-side
}
}
}
Notice the PUBLIC part in the env var:
NUXT_PUBLIC_RECAPTCHA_SITE_KEY=SOMETHING DYNAMIC
This is very strange because we can't access process.env in Nuxt 3
In the Nuxt 3, we are invited to use the runtime config, but this is not always convenient, because the Nuxt application context is required.
But in a situation where we have some plain library, and we don’t want to wrap it in plugins nor composables functions, declaring global variables through vite / webpack is best:
// nuxt.config.ts
export default defineNuxtConfig({
vite: {
define: {
MY_API_URL: JSON.stringify(process.env.MY_API_URL)
}
}
})
And then you can use in any file without dancing with a tambourine:
// some-file.ts
console.log('global var:', MY_API_URL) // replaced by vite/webpack in real value

nomad multiline environment variable

Is there a way to have a multiline environment variable in a nomad template? Trying it directly gives an error about not being able to find the closing quote.
In the docs the only function that's mentioned is | toJSON, but that translates the line feeds into \n so the receiving end needs to do a search-and-replace or some "unJSON" function.
I tried using HEREDOC syntax in the template, but that didn't seem to work either.
Using a here document works fine:
job "example" {
datacenters = ["dc1"]
type = "service"
group "cache" {
task "redis" {
driver = "docker"
config {
image = "redis:7"
}
env {
EXAMPLE = <<EOF
multiline
varibale
is
here
EOF
}
}
}
}

Set environment = 'staging' in Ember deployed with Capistrano 3

I've got a staging environment where I'd like to set a custom set of variables for deploying my Ember.js app and I'm drawing a blank on how to do it correctly. I am using the ember-cli-rails gem. According to the documentation for that:
EMBER_ENV: If set on the environment, the value of EMBER_ENV will be
passed to the ember process as the value of the --environment flag.
I'm just drawing a blank on how to set it on the "environment".
/project/frontend/config/environment.js
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'staging') {
ENV.apiHost = '/app-data';
ENV.contentSecurityPolicy = contentSecurityPolicy;
ENV.torii = {
providers: {
'my-custom-oauth2': {
apiKey: '1234123412341234123412341234',
baseUrl: 'http://www.server.com:9108/oauth/authorize'
}
}
};
}
if (environment === 'production') {
ENV.apiHost = '/app-data';
ENV.contentSecurityPolicy = contentSecurityPolicy;
Things I've tried so far:
Setting export EMBER_ENV='staging' in my deployer user's .profile
Setting set :default_env, { 'EMBER_ENV' => 'staging' } in my /config/deploy/staging.rb file.
Unfortunately, ember cli only support test, development and production as valid environments
The ENV object contains three important keys:
EmberENV can be used to define Ember feature flags (see the Feature
Flags guide).
APP can be used to pass flags/options to your
application instance.
environment contains the name of the current environment (development, production or test).
There are several unofficial solutions to this out there, some of them use ember-cli-deploy and change the settings based on deployTarget value. Others use dotenv to manage each environment settings.
We're dealing with this at the moment and couldn't find a solution that feels right.

Detecting environment with Meteor.js?

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!
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' }
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
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')

Print list of ALL environment variables

I would like to print a list of all environment variables and their values. I searched the Stackoverflow and the following questions come close but don't answer me:
How to discover what is available in lua environment? (it's about Lua environment not the system environment variables)
Print all local variables accessible to the current scope in Lua (again about _G not the os environment variables)
http://www.lua.org/manual/5.1/manual.html#pdf-os.getenv (this is a good function but I have to know the name of the environment variable in order to call it)
Unlike C, Lua doesn't have envp** parameter that's passed to main() so I couldn't find a way to get a list of all environment variables. Does anybody know how I can get the list of the name and value of all environment variables?
Standard Lua functions are based on C-standard functions, and there is no C-standard function to get all the environment variables. Therefore, there is no Lua standard function to do it either.
You will have to use a module like luaex, which provides this functionality.
This code was extracted from an old POSIX binding.
static int Pgetenv(lua_State *L) /** getenv([name]) */
{
if (lua_isnone(L, 1))
{
extern char **environ;
char **e;
if (*environ==NULL) lua_pushnil(L); else lua_newtable(L);
for (e=environ; *e!=NULL; e++)
{
char *s=*e;
char *eq=strchr(s, '=');
if (eq==NULL) /* will this ever happen? */
{
lua_pushstring(L,s);
lua_pushboolean(L,0);
}
else
{
lua_pushlstring(L,s,eq-s);
lua_pushstring(L,eq+1);
}
lua_settable(L,-3);
}
}
else
lua_pushstring(L, getenv(luaL_checkstring(L, 1)));
return 1;
}
You can install the lua-posix module. Alternatively, RedHat installations have POSIX routines built-in, but to enable them, you have to do a trick:
cd /usr/lib64/lua/5.1/
# (replace 5.1 with your version)
ln -s ../../librpmio.so.1 posix.so
# (replace the "1" as needed)
lua -lposix
> for i, s in pairs(posix.getenv()) do print(i,s,"\n") end
The trick is in creating a soft-link to the RPM's "io" directory and to naming the soft-link the same name of the library LUA will attempt to open. If you don't do this, you get:
./librpmio.so: undefined symbol: luaopen_librpmio
or similar.
local osEnv = {}
for line in io.popen("set"):lines() do
envName = line:match("^[^=]+")
osEnv[envName] = os.getenv(envName)
end
this would not work in some cases, like "no valid shell for the user running your app"
An easy 2 liner:
buf = io.popen("env", '*r')
output = buf:read('*a')
print(output) -- or do whatever

Resources