I’m trying to generate and save an LCOV code coverage report file from a mocha test suite for my server in my (non-Typescript) Meteor app. To enable this, I’ve added the lmieulet:meteor-coverage meteor package, the meteortesting:mocha meteor package, and the instanbul babel plugin.
I've also written a ./.coverage.json file:
{
"include": [
"**/*.js",
"**/packages/lmieulet_meteor-coverage.js"
],
"remap": {
"format": ["html", "clover", "cobertura", "json", "json-summary", "lcovonly", "teamcity", "text", "text-summary"]
},
"output": "./.coverage"
}
And added config for the babel plugin in package.json:
"babel": {
"env": {
"COVERAGE": {
"plugins": [
"istanbul"
]
}
}
}
And I’ve written an npm script (named “test-cov”) which includes the necessary env variables to run the test with coverage.
cross-env BABEL_ENV=COVERAGE TEST_CLIENT=0 COVERAGE_OUT_LCOVONLY=1 COVERAGE=1 COVERAGE_VERBOSE=1 COVERAGE_APP_FOLDER=$(pwd)/ meteor test --port 3030 --once --driver-package meteortesting:mocha
With all this set up, I'm expecting the code coverage report to successfully generate when I run "npm run test-cov".
However, when I do run it, I keep getting the following error:
Error: Failed to save lcov coverage... at packages/meteortestingLmocha/server.handlecoverage.js:37:18
I’ve tried:
Switching between the absolute path for ‘output’ in coverage.json file and relative path (./.coverage)
Updating the versions of meteortesting:mocha as well as the overall Meteor version of my app
Opening chmod permissions to 777 for ./.coverage folder (to be written into)
One complication may be that we also have a second testing suite (Jest), but I don’t believe that’s being invoked anywhere as a result of running “test-cov”
Does anyone have an idea of why this isn’t working? I’m at a loss about what to do, partly because the error message here is so brief…
How to set some environment variables from within package.json to be used with npm start like commands?
Here's what I currently have in my package.json:
{
...
"scripts": {
"help": "tagove help",
"start": "tagove start"
}
...
}
I want to set environment variables (like NODE_ENV) in the start script while still being able to start the app with just one command, npm start.
Set the environment variable in the script command:
...
"scripts": {
"start": "node app.js",
"test": "NODE_ENV=test mocha --reporter spec"
},
...
Then use process.env.NODE_ENV in your app.
Note: This is for Mac & Linux only. For Windows refer to the comments.
Just use NPM package cross-env. Super easy. Works on Windows, Linux, and all environments. Notice that you don't use && to move to the next task. You just set the env and then start the next task. Credit to #mikekidder for the suggestion in one of the comments here.
From documentation:
{
"scripts": {
"build": "cross-env NODE_ENV=production OTHERFLAG=myValue webpack --config build/webpack.config.js"
}
}
Notice that if you want to set multiple global vars, you just state them in succession, followed by your command to be executed.
Ultimately, the command that is executed (using spawn) is:
webpack --config build/webpack.config.js
The NODE_ENV environment variable will be set by cross-env
I just wanted to add my two cents here for future Node-explorers. On my Ubuntu 14.04 the NODE_ENV=test didn't work, I had to use export NODE_ENV=test after which NODE_ENV=test started working too, weird.
On Windows as have been said you have to use set NODE_ENV=test but for a cross-platform solution the cross-env library didn't seem to do the trick and do you really need a library to do this:
export NODE_ENV=test || set NODE_ENV=test&& yadda yadda
The vertical bars are needed as otherwise Windows would crash on the unrecognized export NODE_ENV command. I don't know about the trailing space, but just to be sure I removed them too.
Because I often find myself working with multiple environment variables, I find it useful to keep them in a separate .env file (make sure to ignore this from your source control). Then (in Linux) prepend export $(cat .env | xargs) && in your script command before starting your app.
Example .env file:
VAR_A=Hello World
VAR_B=format the .env file like this with new vars separated by a line break
Example index.js:
console.log('Test', process.env.VAR_A, process.env.VAR_B);
Example package.json:
{
...
"scripts": {
"start": "node index.js",
"env-linux": "export $(cat .env | xargs) && env",
"start-linux": "export $(cat .env | xargs) && npm start",
"env-windows": "(for /F \"tokens=*\" %i in (.env) do set %i)",
"start-windows": "(for /F \"tokens=*\" %i in (.env) do set %i) && npm start",
}
...
}
Unfortunately I can't seem to set the environment variables by calling a script from a script -- like "start-windows": "npm run env-windows && npm start" -- so there is some redundancy in the scripts.
For a test you can see the env variables by running npm run env-linux or npm run env-windows, and test that they make it into your app by running npm run start-linux or npm run start-windows.
Try this on Windows by replacing YOURENV:
{
...
"scripts": {
"help": "set NODE_ENV=YOURENV && tagove help",
"start": "set NODE_ENV=YOURENV && tagove start"
}
...
}
#luke's answer was almost the one I needed! Thanks.
As the selected answer is very straightforward (and correct), but old, I would like to offer an alternative for importing variables from a .env separate file when running your scripts and fixing some limitations to Luke's answer.
Try this:
::: .env file :::
# This way, you CAN use comments in your .env files
NODE_PATH="src/"
# You can also have extra/empty lines in it
SASS_PATH="node_modules:src/styles"
Then, in your package json, you will create a script that will set the variables and run it before the scripts you need them:
::: package.json :::
scripts: {
"set-env": "export $(cat .env | grep \"^[^#;]\" |xargs)",
"storybook": "npm run set-env && start-storybook -s public"
}
Some observations:
The regular expression in the grep'ed cat command will clear the comments and empty lines.
The && don't need to be "glued" to npm run set-env, as it would be required if you were setting the variables in the same command.
If you are using yarn, you may see a warning, you can either change it to yarn set-env or use npm run set-env --scripts-prepend-node-path && instead.
Different environments
Another advantage when using it is that you can have different environment variables.
scripts: {
"set-env:production": "export $(cat .production.env | grep \"^[^#;]\" |xargs)",
"set-env:development": "export $(cat .env | grep \"^[^#;]\" |xargs)",
}
Please, remember not to add .env files to your git repository when you have keys, passwords or sensitive/personal data in them!
UPDATE: This solution may break in npm v7 due to npm RFC 21
CAVEAT: no idea if this works with yarn
npm (and yarn) passes a lot of data from package.json into scripts as environment variables. Use npm run env to see them all. This is documented in https://docs.npmjs.com/misc/scripts#environment and is not only for "lifecycle" scripts like prepublish but also any script executed by npm run.
You can access these inside code (e.g. process.env.npm_package_config_port in JS) but they're already available to the shell running the scripts so you can also access them as $npm_... expansions in the "scripts" (unix syntax, might not work on windows?).
The "config" section seems intended for this use:
"name": "myproject",
...
"config": {
"port": "8010"
},
"scripts": {
"start": "node server.js $npm_package_config_port",
"test": "wait-on http://localhost:$npm_package_config_port/ && node test.js http://localhost:$npm_package_config_port/"
}
An important quality of these "config" fields is that users can override them without modifying package.json!
$ npm run start
> myproject#0.0.0 start /home/cben/mydir
> node server.js $npm_package_config_port
Serving on localhost:8010
$ npm config set myproject:port 8020
$ git diff package.json # no change!
$ cat ~/.npmrc
myproject:port=8020
$ npm run start
> myproject#0.0.0 start /home/cben/mydir
> node server.js $npm_package_config_port
Serving on localhost:8020
See npm config and yarn config docs.
It appears that yarn reads ~/.npmrc so npm config set affects both, but yarn config set writes to ~/.yarnrc, so only yarn will see it :-(
For a larger set of environment variables or when you want to reuse them you can use env-cmd.
As a plus, the .env file would also work with direnv.
./.env file:
# This is a comment
ENV1=THANKS
ENV2=FOR ALL
ENV3=THE FISH
./package.json:
{
"scripts": {
"test": "env-cmd mocha -R spec"
}
}
This will work in Windows console:
"scripts": {
"setAndStart": "set TMP=test&& node index.js",
"otherScriptCmd": "echo %TMP%"
}
npm run aaa
output:
test
See this answer for details.
suddenly i found that actionhero is using following code, that solved my problem by just passing --NODE_ENV=production in start script command option.
if(argv['NODE_ENV'] != null){
api.env = argv['NODE_ENV'];
} else if(process.env.NODE_ENV != null){
api.env = process.env.NODE_ENV;
}
i would really appreciate to accept answer of someone else who know more better way to set environment variables in package.json or init script or something like, where app bootstrapped by someone else.
use git bash in windows. Git Bash processes commands differently than cmd.
Most Windows command prompts will choke when you set environment variables with NODE_ENV=production like that. (The exception is Bash on Windows, which uses native Bash.) Similarly, there's a difference in how windows and POSIX commands utilize environment variables. With POSIX, you use: $ENV_VAR and on windows you use %ENV_VAR%. - cross-env doc
{
...
"scripts": {
"help": "tagove help",
"start": "env NODE_ENV=production tagove start"
}
...
}
use dotenv package to declare the env variables
For single environment variable
"scripts": {
"start": "set NODE_ENV=production&& node server.js"
}
For multiple environment variables
"scripts": {
"start": "set NODE_ENV=production&& set PORT=8000&& node server.js"
}
When the NODE_ENV environment variable is set to 'production' all devDependencies in your package.json file will be completely ignored when running npm install. You can also enforce this with a --production flag:
npm install --production
For setting NODE_ENV you can use any of these methods
method 1: set NODE_ENV for all node apps
Windows :
set NODE_ENV=production
Linux, macOS or other unix based system :
export NODE_ENV=production
This sets NODE_ENV for current bash session thus any apps started after this statement will have NODE_ENV set to production.
method 2: set NODE_ENV for current app
NODE_ENV=production node app.js
This will set NODE_ENV for the current app only. This helps when we want to test our apps on different environments.
method 3: create .env file and use it
This uses the idea explained here. Refer this post for more detailed explanation.
Basically, you create a .env file and run some bash scripts to set them on the environment.
To avoid writing a bash script, the env-cmd package can be used to load the environment variables defined in the .env file.
env-cmd .env node app.js
method 4: Use cross-env package
This package allows environment variables to be set in one way for every platform.
After installing it with npm, you can just add it to your deployment script in package.json as follows:
"build:deploy": "cross-env NODE_ENV=production webpack"
{
...
"scripts": {
"start": "ENV NODE_ENV=production someapp --options"
}
...
}
Most elegant and portable solution:
package.json:
"scripts": {
"serve": "export NODE_PRESERVE_SYMLINKS_MAIN=1 && vue-cli-service serve"
},
Under windows create export.cmd and put it somewhere to your %PATH%:
#echo off
set %*
If you:
Are currently using Windows;
Have git bash installed;
Don't want to use set ENV in your package.json which makes it only runnable for Windows dev machines;
Then you can set the script shell of node from cmd to git bash and write linux-style env setting statements in package.json for it to work on both Windows/Linux/Mac.
$ npm config set script-shell "C:\\Program Files\\git\\bin\\bash.exe"
Although not directly answering the question I´d like to share an idea on top of the other answers. From what I got each of these would offer some level of complexity to achieve cross platform independency.
On my scenario all I wanted, originally, to set a variable to control whether or not to secure the server with JWT authentication (for development purposes)
After reading the answers I decided simply to create 2 different files, with authentication turned on and off respectively.
"scripts": {
"dev": "nodemon --debug index_auth.js",
"devna": "nodemon --debug index_no_auth.js",
}
The files are simply wrappers that call the original index.js file (which I renamed to appbootstrapper.js):
//index_no_auth.js authentication turned off
const bootstrapper = require('./appbootstrapper');
bootstrapper(false);
//index_auth.js authentication turned on
const bootstrapper = require('./appbootstrapper');
bootstrapper(true);
class AppBootStrapper {
init(useauth) {
//real initialization
}
}
Perhaps this can help someone else
Running a node.js script from package.json with multiple environment variables:
package.json file:
"scripts": {
"do-nothing": "set NODE_ENV=prod4 && set LOCAL_RUN=true && node ./x.js",
},
x.js file can be as:
let env = process.env.NODE_ENV;
let isLocal = process.env.LOCAL_RUN;
console.log("ENV" , env);
console.log("isLocal", isLocal);
You should not set ENV variables in package.json. actionhero uses NODE_ENV to allow you to change configuration options which are loaded from the files in ./config. Check out the redis config file, and see how NODE_ENV is uses to change database options in NODE_ENV=test
If you want to use other ENV variables to set things (perhaps the HTTP port), you still don't need to change anything in package.json. For example, if you set PORT=1234 in ENV and want to use that as the HTTP port in NODE_ENV=production, just reference that in the relevant config file, IE:
# in config/servers/web.js
exports.production = {
servers: {
web: function(api){
return {
port: process.env.PORT
}
}
}
}
In addition to use of cross-env as documented above, for setting a few environment variables within a package.json 'run script', if your script involves running NodeJS, then you can set Node to pre-require dotenv/config:
{
scripts: {
"eg:js": "node -r dotenv/config your-script.js",
"eg:ts": "ts-node -r dotenv/config your-script.ts",
"test": "ts-node -r dotenv/config -C 'console.log(process.env.PATH)'",
}
}
This will cause your node interpreter to require dotenv/config, which will itself read the .env file in the present working directory from which node was called.
The .env format is lax or liberal:
# Comments are permitted
FOO=123
BAR=${FOO}
BAZ=Basingstoke Round About
#Blank lines are no problem
Note : In order to set multiple environment variable, script should goes like this
"scripts": {
"start": "set NODE_ENV=production&& set MONGO_USER=your_DB_USER_NAME&& set MONGO_PASSWORD=DB_PASSWORD&& set MONGO_DEFAULT_DATABASE=DB_NAME&& node app.js",
},
I am using ES6 modules by adding the --experimental-modules arguments to Node. Running node --experimental-modules app.mjs works perfectly fine. However, when I run the same command with pm2 I get the following error:
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module
My current pm2 config file looks like this:
"apps": [
{
"name": "api",
"script": "app.mjs",
"exec_mode": "cluster",
"instances": "max",
"node_args": "--experimental-modules",
"env": {
variables here..
}
}
],
I have also tried using esm instead like this:
"node_args": "-r esm"
In both cases they return the same [ERR_REQUIRE_ESM] error
Does anyone have a solution on how to use es6 modules with pm2 or is it broken at the moment?
UPDATE
Starting from Node.js version 12.14.1, you don't have to add the --experimental-modules argument, so if you update node, it should work without any changes to your configuration.
ORIGINAL ANSWER
A workaround for this problem:
In your package.json file, add a new script:
"scripts": {
//Add this one:
"safestart":"node --experimental-modules app.mjs"
},
Run this PM2 command:
pm2 start npm -- run safestart
If you do not want to update node or another approach is using esm package
See my answer here.
I have compiled my app via create react app: yarn build //code is minified and obfuscated as expected
I have then deployed the app via both firebase serve and firebase deploy.
my firebase.json:
{
"database": {
"rules": "database.rules.json"
},
"hosting": {
"public": "build",
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
All is deployed "almost as expected", with 2 caveats:
inside Chrome developer tools/ Sources tab, my entire js codebase is listed with no minification and or obfuscation!
my fonts are not being deployed as the media folder doesnt seem to transfer
The structure looks nothing like the build folder which contains the media... (necessary for fonts):
Am I setting something up incorrectly, deploying the wrong folder or possibly not ignoring something I should be? Exposing the entire js stack unminified and or without any obfuscation seems very "un-secure"...
Again, and as always any and all direction is greatly appreciated!
Strongly advise to refer to the create-react-app github discussion here about this matter but as a quick workaround you can add the following to your package.json scripts:
"scripts": {
...
"build": "npm run build-css && react-scripts build && yarn run delete-maps",
"delete-maps": "rm ./build/static/js/*.map && rm ./build/static/css/*.map",
...
}
This will however in the short run remove all of your source code from the Source tab in developer tools...
Prefixing GENERATE_SOURCEMAP=false to your build target works too (which obviously doesn't generate sourcemap). In package.json file.
GENERATE_SOURCEMAP=false react-scripts build
How do I debug a gulp task defined in my gulpfile.js with a debugger such as the Google Chrome debugger, stepping through the task's code line by line?
With Node.js version 6.3+ you can use the --inspect flag when running your task.
To debug a gulp task named css:
Find out where your gulp executable lives. If gulp is installed locally, this will be at node_modules/.bin/gulp. If gulp is installed globally, run which gulp (Linux/Mac) or where gulp (Windows) in a terminal to find it.
Run one of these commands according to your version of Node.js. If required, replace ./node_modules/.bin/gulp with the path to your gulp installation from step 1.
Node.js 6.3+: node --inspect --debug-brk ./node_modules/.bin/gulp css
Node.js 7+: node --inspect-brk ./node_modules/.bin/gulp css
Use Chrome to browse to chrome://inspect.
The --debug-brk (Node.js 6.3+) and --inspect-brk (Node.js 7+) flags are used to pause code execution on the first line of code of your task. This gives you a chance to open up the Chrome debugger and set breakpoints before the task finishes.
If you don't want the debugger to pause on first line of code, just use the --inspect flag.
You can also install the Node.js Inspector Manager (NIM) extension for Chrome to help with step 3. This will automatically open up a Chrome tab with the debugger ready to go, as an alternative to manually browsing to a URL.
For anyone using VS Code 1.10+
Open the debug panel.
Click on the settings icon.
Click on Add Configuration button.
Choose Node.js: Gulp Task.
This is how your launch.json file should look.
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Gulp task",
"program": "${workspaceFolder}/node_modules/gulp/bin/gulp.js",
"args": [
"yourGulpTaskName"
]
}
]
}
If you are using webstorm you can right click the task in the gulp panel and select debug.
Thanks user2943490, on Windows I found this version worked for me:
node --inspect --debug-brk ./node_modules/gulp/bin/gulp.js --verbose
If you are using gulp-nodemon you can do this in your gulpfile.
Just pass it the execMap option:
gulp.task('default', function() {
nodemon({
script: 'server.js',
ext: 'js',
execMap: {
js: "node --inspect"
}
})
}
Hope this helps.
Version (node v8.11.3, npm 6.2.0, gulp 3.9.1)
Windows 10 & git bash
Install Node.js V8 --inspector Manager (NiM) & set to your preference
Try this:
node --inspect-brk ./node_modules/gulp/bin/gulp.js --verbose
I liked the answer of #Avi Y. but I suppose people would had appreciated a more complete script :
gulp.task('nodemon', ['sass'], function(cb) {
var started = false;
consoleLog('nodemon started');
return nodemon({
//HERE REMOVE THE COMMENT AT THE BEGINING OF THE LINE YOU NEED
//exec: 'node --inspect --debug-brk node_modules/gulp/bin/gulp.js',
exec: 'node --inspect --debug-brk',
//exec: 'node --inspect',
script: path.server,
ignore: ['*/gulpfile.js', 'node_modules/*'],
verbose: true
}).on('start', function() {
if (!started) {
cb();
started = true;
}
}).on('restart', function() {
consoleLog('nodemon restarted the server');
});});