Node.js docs about a fs module says (https://nodejs.org/api/fs.html#fs_file_system):
To get a trace to the original call site, set the NODE_DEBUG environment variable:
And an example of setting an fs env variable:
$ env NODE_DEBUG=fs node script.js
fs.js:66
throw err;
^
Error: EISDIR, read
at rethrow (fs.js:61:21)
at maybeCallback (fs.js:79:42)
at Object.fs.readFile (fs.js:153:18)
at bad (/path/to/script.js:2:17)
at Object.<anonymous> (/path/to/script.js:5:1)
<etc.>
However, if I set fs env variable upfront in command line or using process.env in the script, the variable is set but doesn't work, no trace is shown:
Upfront in command line:
$ env NODE_DEBUG=fs // set before running a script
$ node script.js // doesn't bring the trace
In the script:
'use strict';
process.env.NODE_DEBUG = 'fs'; // set it on the second line of a script
<...> // script goes here
I both cases the result is as follows, no trace, though NODE_DEBUG=fs is set:
fs.js:81
throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
^
Error: EISDIR, read
at Error (native)
The question is.
Why command line inline variable setting works:
$ env NODE_DEBUG=fs node script.js,
but other ways of setting it do not work?
env runs a program with a particular environment. If it isn’t passed one, it lists environment variables instead; it can’t modify its parent process’s enivronment. To set an environment variable for the current session, use export:
export NODE_DEBUG=fs
node script.js
Shells will let you omit both export and env, though:
NODE_DEBUG=fs node script.js # Like env; doesn’t create an exported NODE_DEBUG
NODE_DEBUG=fs
node script.js
Related
For my testing framework I'm using dotenv to read and initialize environment variables for different test environments. Now I want to use a specific environment variable value as a part of the value and the name of another environment variables.
So, I set the env var export INSTANCE=1 before initializing the env file with dotenv.
This is my env file with all the env vars I want to initialize with dotenv:
# INSTANCE as part of env var value
MY_DOMAIN="http://mypage/"$INSTANCE""
# INSTANCE as part of env var name
SUBDOMAIN"$INSTANCE"="/mysubdomain"
And this metric is also not working:
# INSTANCE as part of env var value
MY_DOMAIN=http://mypage/${INSTANCE}
# INSTANCE as part of env var name
SUBDOMAIN${INSTANCE}=/mysubdomain
This is possible doing it via bash with
export MY_DOMAIN="http://mypage/"$INSTANCE"" SUBDOMAIN"$INSTANCE"="/mysubdomain"
echo $MY_DOMAIN
http://mypage/1
echo $SUBDOMAIN1
/mysubdomain
But using dotenv it is not working for me. I have the following code:
const dotenv = require("dotenv");
var result = dotenv.config({ path: '/path/to/my/env/file' });
console.log(result.parsed);
The console.log produces the following result:
{
MY_DOMAIN:'http://mypage/"$INSTANCE"'
}
So, the env var INSTANCE can not be used, the value will be ignored. Are there any solution to solve my issue?
I have found a solution using dotenv-expand :)
I am trying to set and get environment variable in node js .I tried like this
I create the test.js file
And add this line
console.log(process.env.NODE_ENV);
Run like this
set NODE_ENV=production&&node test.js
It gives me undefined
NODE_ENV=production node test.js on linux and $env:NODE_ENV = 'production'; node test.js in powershell.
In addition to the accepted answer:
From nodejs docs
It is possible to modify this object, but such modifications will not be reflected outside the Node.js process.
So you can also do something like:
process.env.foo = 'bar';
console.log(process.env.foo);
Assigning a property on process.env will implicitly convert the value to a string.
process.env.test = null;
console.log(process.env.test);
// => 'null'
Note: There are some env variables which you can set only before any codes are executed.
Also note:
On Windows operating systems, environment variables are case-insensitive.
process.env.TEST = 1;
console.log(process.env.test);
// => 1
1. create a package.json file.
2. install the dotenv npm package
make a .env file in your root directory.
//env
NODE_ENV=development
PORT=8626
# Set your database/API connection information here
API_KEY=**************************
API_URL=**************************
Now if you want to call your port in any file or server.js it will be like this.
const port = process.env.PORT;
console.log(`Your port is ${port}`);
The documentation for Vue CLI 3 says here https://cli.vuejs.org/guide/mode-and-env.html#using-env-variables-in-client-side-code:
You can have computed env vars in your vue.config.js file. They still need to be prefixed with VUE_APP_. This is useful for version info process.env.VUE_APP_VERSION = require('./package.json').version
This is exactly what I want to do. But I couldn't find out how to actually define the env var there in vue.config.js. I tried:
module.exports = {
process.env.VUE_APP_VERSION: require("../package.json").version,
...
}
But it just produces an error:
ERROR SyntaxError: Unexpected token .
/Users/lhermann/htdocs/langify/frontend/vue.config.js:2
process.env.VUE_APP_VERSION: require("../package.json").version,
^
Does anyone know?
The environment variables are not part of the config export, you just set them in the vue.config.js file, eg
process.env.VUE_APP_VERSION = require('./package.json').version
module.exports = {
// other config, eg configureWebpack
}
I've raised a feature-request to get an example added to the docs ~ https://github.com/vuejs/vue-cli/issues/2864
Common Environment Variables:
According to Environment Variables and Modes documentation, you can specify env variables by placing .env files in your project root.
The variables will automatically be accessible under process.env.variableName in your project. Loaded variables are also available to all vue-cli-service commands, plugins and dependencies.
.env # loaded in all cases
.env.local # loaded in all cases, ignored by git
.env.[mode] # only loaded in specified mode
.env.[mode].local # only loaded in specified mode, ignored by git
Your .env file(s) should look like this:
VUE_APP_MY_ENV_VARIABLE=value
VUE_APP_ANOTHER_VARIABLE=value
Note that only variables that start with VUE_APP_ will be statically embedded into the client bundle with webpack.DefinePlugin.
Computed Environment Variables:
If you want variables that need pre-processing, you can use chainWebpack property of vue.config.js to inject anything you want:
// vue.config.js
module.exports = {
// ...,
chainWebpack: config => {
config.plugin('define').tap(args => {
args[0]['process.env'].APP_VERSION = `"${require("../package.json").version}"`
return args
})
}
// ...
}
Using this method, you can inject anything, with any names you want; you are not bound by the VUE_APP_ limitation.
I'm running a file main.js using Casper.js via casperjs main.js, which uses a module ./lib/myUtils.js, which in turn uses
var utils = require('utils')
But running casperjs main.js throws the error
Error: Cannot find module 'utils'
phantomjs://bootstrap.js:289
phantomjs://bootstrap.js:254 in require
/Users/username/casper-test/lib/myUtils.js:2
/Users/username/casper-test/lib/myUtils.js:63
TypeError: 'undefined' is not a function (evaluating 'myUtils.loadCookies()')
/Users/username/casper-test/main.js:104
The functions being imported have "use strict"; in their first line.
However putting the code from myUtils.js directly into main.js avoids the error. Why is this?
I suppose you need to insert var require = patchRequire(require); at the beginning of your file ( myUtils.js ).
when I run a test in node.js with mocha, how I can set temporal environment variables?
in a module, I have a variable depending of a environment variable
var myVariable = proccess.env.ENV_VAR;
now I use the rewire module,
var rewire = require('rewire');
var myModule = rewire('../myModule');
myModule.__set__('myVariable', 'someValue');
exist a more simple way? without the rewire module?
In your myModule.js file, export a function that takes the variable as an argument eg:
module.exports = function (var) {
// return what you were exporting before
};
Then when you require it, require it like so:
var myModule = require('../myModule')(process.env.ENV_VAR);
My first instinct was to simply set the env var at the top of the test.js before any require statements. However, this may not work for you if you have a module that depends on a env var, and it is required multiple times in the same test run. say you have an env dependent module called mode.js:
module.exports = {
MODE : process.env.ENV_VAR
};
If you add a single test file called bTest.js with
process.env.ENV_VAR= "UNIT_TEST_MODE"
const mode = require('./mode.js')
// describe some tests scenarios that use mode.MODE
...
you will be OK. but if you add a second test file
const mode = require('./mode.js')
// describe some more tests scenarios that use mode.MODE
...
and name it aTest.js, the new file will run first in your suite and mode.MODE will be undefined for all subsequent test js files. The require command won't actually reload the same module multiple times.
Let's assume you aren't able to use the dotenv package in your tests. If so, you can set values on the process.env programmatically in the mocha config file. By default, this is found in .mocharc.json or .mocha.yml, but this can easily be translated to .mocharc.js . Referring to the sample js file here: https://github.com/mochajs/mocha/blob/master/example/config/.mocharc.js
So your .mocharc.js could be
"use strict";
process.env.ENV_VAR = "UNIT_TEST_MODE";
// end of .mocharc.js
and ENV_VAR will be set before mocha requires or runs any of your modules.
Even if you are using dotenv , you can choose to flip set other dotenv option from inside your mochajs config that you might not want to set on your local dev server's .env file. That way, your .env.mocha vars will be available to individual modules that don't require dotenv.
"use strict";
require('dotenv').config({ debug: process.env.DEBUG, { path: '/full/custom/path/to/.env.mocha' } })`.
// end of .mocharc.js
Although in the second case, you may be better off just setting the dotenv env path as part of the test command in your package.json:
node -r dotenv/config /node_modules/mocha/bin/_mocha dotenv_config_path=/full/custom/path/to/.env.mocha