How to get environment variable in npm script? - node.js

I am trying to access an enviroment variable in the npm script itself like so:
"scripts": {
"test": "istanbul cover node_modules/.bin/_mocha --root ../SERVER/routes -- --recursive"
},
And start this script like so:
SERVER=somewhere npm test
How can I get the resolved value of SERVER variable in the npm script in the package.json itself?

For the windows users, you may use your variables like this: %SERVER% instead of $SERVER.
Or better approach to use cross-env module which will allow you to do it like linux on all platforms:
npm i cross-env
And use it :
"scripts": {
"test": "cross-env-shell \"istanbul cover node_modules/.bin/_mocha --root ../$SERVER/routes -- --recursive\""
}

Will using $SERVER work for you?
"scripts": {
"test": "istanbul cover node_modules/.bin/_mocha --root ../$SERVER/routes -- --recursive"
}

Related

Npm workspaces - call workspace script from root package

I'm struggling with multiple npm packages in a root git repository with custom dev scripts to handle launch, compile, build and so on. Now I came across npm workspaces and wanted to use this stunning new feature in my following project structure but I can't get it to work:
projectx (root)
- package.json
- apps
-- backend
-- src
-- package.json (name: #projectx/backend, scripts: "dev":"ts-node or whatever")
-- common
-- src
-- package.json (name: #projectx/common)
-- frontend
-- src
-- package.json (name: #projectx/frontend, scripts: "dev":"webpack")
My root package.json contains:
{
"name": "packagex",
"version": "1.0.0",
"description": "",
"main": "index.js",
"private": "true",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"back:dev": "npm workspace #projectx/backend dev",
"front:dev": "npm workspace #projectx/frontend dev",
"dev": "run-p back:dev front:dev"
},
"workspaces": [
"apps/*"
],
"repository": {
"type": "git",
"url": "git_url"
},
"author": "me",
"license": "ISC",
"devDependencies": {
"npm-run-all": "^4.1.5"
}
}
And now I want to start backend and frontend with npm-run-all and the command on root: npm run dev which results in:
And I also want to share the common package with backend and frontend, which should be possible in this case. Maybe anobody else is facing the same problem or has some ideas what I am doing wrong here.
npm#7.7.0 added a way to call scripts from child packages/workspaces, here are some examples based on your original:
Running a script named "dev" in all workspaces located under apps/backend:
npm run dev -w apps/backend
Running a script named "dev" in all workspaces:
npm run dev --ws
Running a script named "dev" in a package named #projectx/frontend:
npm run dev -w #projectx/frontend
More info:
Related CHANGELOG entry: https://github.com/npm/cli/releases/tag/v7.7.0
Docs: https://docs.npmjs.com/cli/v7/commands/npm-run-script#workspaces-support
Blog post: https://dev.to/ruyadorno/npm-workspaces-npm-run-and-exec-1lg0
Your "workspaces" property in package.json looks right. I'm using NPM Workspaces and it's working well, but it's still missing a lot of features so you need to wire things up yourself. I also don't think npm worksace is a command (but maybe for the future?), so here's a checklist to get it to work:
Make sure you're using Node 15+ and NPM 7+
Set all package.json to "private": true,
Delete all package-lock.json inside of your project, go to the root, then npm install. It should generate one root level package-lock.json that contains all dependencies for your workspaces
Since you're using npm-run-all, add this to your scripts:
"scripts": {
"back:dev": "cd apps/backend && npm run dev",
"front:dev": "cd apps/fontend && npm run dev",
"dev": "npm-run-all build --parallel back:dev front:dev"
}
Then start it with npm run dev.
Note, you may want to consider using start scripts instead of dev to shorten the command you need to type (e.g. npm start instead of npm run dev), but npm run dev will still be fine.
In root package.json you can also add short name for each package:
"scripts": {
"api": "npm --workspace=#app/api run",
}
#app/api is a name in package.json
And run scripts in ./packages/api folder from root like so:
npm run api lint
npm run api dev
I think you wish to:
keep scripts and dependencies separate (thus the 4 package.json files), for ease of maintenance
May I suggest a work-around without workspaces that might do what you're after:
{
...
"scripts": {
"//back:dev": "npm workspace #projectx/backend dev",
"back:dev": "npm --prefix apps/backend dev",
"//front:dev": "npm workspace #projectx/frontend dev",
"front:dev": "npm --prefix apps/frontend dev",
"dev": "run-p back:dev front:dev"
},
"//workspaces": [
"apps/*"
],
"devDependencies": {
"#local/back": "file:apps/backend",
"#local/front": "file:apps/frontend",
"npm-run-all": "^4.1.5"
}
}
The npm --prefix runs npm scripts in another folder than the current one.
The #local/back dependencies are not necessary for that, but I've found such useful if eg. a package depends on another. You might use that trick to reach for the common by:
"dependencies": {
"#local/common": "file:../common"
}
I wished a week ago that workspaces would offer a better solution, but didn't find any benefit over the above mechanisms.
I would also like workspaces to:
only expose those files in the files entry of the particular package.json (now, all are shown)
only allow import to paths in the exports of the particular package.json, if it has one
See
NPM Workspaces monorepo - share local package's distribution folder as root instead of the entire source files

Difference between start and dev script in package.json file

In almost all of the docs I've come across so far, most of the time I have seen the start and the dev script being used for a similar kind of functionality. following are 2 examples:
1.
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index",
"dev": "nodemon index"
},
"scripts": {
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
"start": "npm run dev",
So, please help me in understanding, what exactly is the difference between the two in package.json file used for NodeJs. Under what circumstances does mentioning the 2 at the same time make sense.
P.S: I'm new to javascript and node.js. Hence please forgive in case of a silly mistake. Thanks in advance :)
Start is a script handled by default by npm. You can use it without the keyword run:
npm start
dev is a custom script, the name has no significance fr npm. You need to use the keyword run:
# npm run <script name>
npm run dev
documentation for start: https://docs.npmjs.com/cli/v6/commands/npm-start
documentation for run-script: https://docs.npmjs.com/cli/v6/commands/npm-run-script
In other words, start will override the default npm command. By default, npm will run node index.js on start. The start script always exists even if you don't declare it. That is not the case for dev.

Is it possible to set a dotenv variable from package.json script?

I am using dotenv in my project to get variables from a .env file. I would like to be able to set a value in the .env(dotenv) file from package.json when running npm test. Something similar to this:
"scripts": {
"test": "set ENV=test mocha './test/**/*.spec.js'",
"start": "node app"
}
my .env file is simply this:
ENV = development
I'm using windows.
Thanks in advance for any help!
You can use
"test": "ENV=test mocha './test/**/*.spec.js'"
in your npm script on Linux, and use
"test": "set ENV=test&&mocha './test/**/*.spec.js'"
on Windows.
BTW, if you need to cross platform, use cross-env so that your code can run on both Windows and Linux.
You can also use require.
For example, you have a ./test/test.env.js
// test/test.env.js
process.env.ENV = 'test';
and use require in your npm script like this:
"test": "mocha --require 'test/test.env.js' './test/**/*.spec.js'"
Yes you can do that, you can pass environment variables through commands too.
i.e. with your scripts:-
"scripts": {
"test": "set ENV=test mocha './test/**/*.spec.js'",
"start": "ENV=test node app.js" //NOTICE I HAVE CHANGED THIS.
}
Just by using, I don't know how to help about the test script, I don't understand that, but I believe it must be something like this
"test": "ENV=test mocha './test/**/*.spec.js'"

NPM: How can I hook SET NODE_ENV in package.json's prestart script?

I have a basic App created using npm init -y. In package.json I have a main entry which points to server.js.
{
"name": "rest-api",
"version": "1.0.0",
"description": "",
"main": "server.js",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"prestart": "SET NODE_ENV=dev"
}
I am trying to set the NODE_ENV variable in prestart and let npm to call main to invoke npm start. But environment variable set in the prestart is not carry forwarded and is undefined. When I run 'npm start', console outputs that both commands are executed in order.
PS D:\test\RestAPI> npm start
> rest-api#1.0.0 prestart D:\test\RestAPI
> set NODE_ENV=dev
> rest-api#1.0.0 start D:\test\RestAPI
> node server.js
undefined
[undefined] Listening on http://localhost:3000
but when I print the variable from the app, it is undefined. Is there anything that I am doing wrong here, or is this how it is supposed to behave? Is there a way to invoke and set env variable using 'SET NODE_ENV=dev' without chaining it to 'node server.js'
When I combine both in the 'start' as below, then the environment variable is set.
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "set NODE_ENV=dev && node server.js"
}
I am testing this on Windows 10, npm version 3.10.10. Appreciate your help.
I know how this can be done in package.json using 'start'. This question is specific to how this can be achieved through 'prestart'.
Thanks.
The short answer is NOT possible.
1. Why :
this is not be possible because each script executed by different processes that npm spawns for this purpose which has its own environment variables.
To realise that, create test project and configure both scripts to be like
"start": "pause&&set VAR1",
"prestart" : "pause&&set VAR1=value&&set VAR1&&pause",
On windows open the task manager and pay close attention how many cmd process es are listed before running the script.
run the command "npm start" and at each request "press any key to continue..." just notice how processes created are created. I attached screenshots for this in order
2. Unless :
you change how npm executes different scripts to use one cmd for all the scripts which I think is complicated and probably will create bugs.
If you want to chain scripts and add env variables along the way then checkout the example given in the cross-env package:
{
"scripts": {
"parentScript": "cross-env GREET=\"Joe\" npm run childScript",
"childScript": "cross-env-shell \"echo Hello $GREET\""
}
}

Run two tasks/scripts that both "hog the terminal" [duplicate]

In my package.json I have these two scripts:
"scripts": {
"start-watch": "nodemon run-babel index.js",
"wp-server": "webpack-dev-server",
}
I have to run these 2 scripts in parallel everytime I start developing in Node.js. The first thing I thought of was adding a third script like this:
"dev": "npm run start-watch && npm run wp-server"
... but that will wait for start-watch to finish before running wp-server.
How can I run these in parallel? Please keep in mind that I need to see the output of these commands. Also, if your solution involves a build tool, I'd rather use gulp instead of grunt because I already use it in another project.
Use a package called concurrently.
npm i concurrently --save-dev
Then setup your npm run dev task as so:
"dev": "concurrently --kill-others \"npm run start-watch\" \"npm run wp-server\""
If you're using an UNIX-like environment, just use & as the separator:
"dev": "npm run start-watch & npm run wp-server"
Otherwise if you're interested on a cross-platform solution, you could use npm-run-all module:
"dev": "npm-run-all --parallel start-watch wp-server"
From windows cmd you can use start:
"dev": "start npm run start-watch && start npm run wp-server"
Every command launched this way starts in its own window.
You should use npm-run-all (or concurrently, parallelshell), because it has more control over starting and killing commands. The operators &, | are bad ideas because you'll need to manually stop it after all tests are finished.
This is an example for protractor testing through npm:
scripts: {
"webdriver-start": "./node_modules/protractor/bin/webdriver-manager update && ./node_modules/protractor/bin/webdriver-manager start",
"protractor": "./node_modules/protractor/bin/protractor ./tests/protractor.conf.js",
"http-server": "./node_modules/http-server/bin/http-server -a localhost -p 8000",
"test": "npm-run-all -p -r webdriver-start http-server protractor"
}
-p = Run commands in parallel.
-r = Kill all commands when one of them finishes with an exit code of zero.
Running npm run test will start Selenium driver, start http server (to serve you files) and run protractor tests. Once all tests are finished, it will close the http server and the selenium driver.
I've checked almost all solutions from above and only with npm-run-all I was able to solve all problems. Main advantage over all other solution is an ability to run script with arguments.
{
"test:static-server": "cross-env NODE_ENV=test node server/testsServer.js",
"test:jest": "cross-env NODE_ENV=test jest",
"test": "run-p test:static-server \"test:jest -- {*}\" --",
"test:coverage": "npm run test -- --coverage",
"test:watch": "npm run test -- --watchAll",
}
Note run-p is shortcut for npm-run-all --parallel
This allows me to run command with arguments like npm run test:watch -- Something.
EDIT:
There is one more useful option for npm-run-all:
-r, --race - - - - - - - Set the flag to kill all tasks when a task
finished with zero. This option is valid only
with 'parallel' option.
Add -r to your npm-run-all script to kill all processes when one finished with code 0. This is especially useful when you run a HTTP server and another script that use the server.
"test": "run-p -r test:static-server \"test:jest -- {*}\" --",
I have a crossplatform solution without any additional modules. I was looking for something like a try catch block I could use both in the cmd.exe and in the bash.
The solution is command1 || command2 which seems to work in both enviroments same. So the solution for the OP is:
"scripts": {
"start-watch": "nodemon run-babel index.js",
"wp-server": "webpack-dev-server",
// first command is for the cmd.exe, second one is for the bash
"dev": "(start npm run start-watch && start npm run wp-server) || (npm run start-watch & npm run wp-server)",
"start": "npm run dev"
}
Then simple npm start (and npm run dev) will work on all platforms!
If you replace the double ampersand with a single ampersand, the scripts will run concurrently.
How about forking
Another option to run multiple Node scripts is with a single Node script, which can fork many others. Forking is supported natively in Node, so it adds no dependencies and is cross-platform.
Minimal example
This would just run the scripts as-is and assume they're located in the parent script's directory.
// fork-minimal.js - run with: node fork-minimal.js
const childProcess = require('child_process');
let scripts = ['some-script.js', 'some-other-script.js'];
scripts.forEach(script => childProcess.fork(script));
Verbose example
This would run the scripts with arguments and configured by the many available options.
// fork-verbose.js - run with: node fork-verbose.js
const childProcess = require('child_process');
let scripts = [
{
path: 'some-script.js',
args: ['-some_arg', '/some_other_arg'],
options: {cwd: './', env: {NODE_ENV: 'development'}}
},
{
path: 'some-other-script.js',
args: ['-another_arg', '/yet_other_arg'],
options: {cwd: '/some/where/else', env: {NODE_ENV: 'development'}}
}
];
let runningScripts= [];
scripts.forEach(script => {
let runningScript = childProcess.fork(script.path, script.args, script.options);
// Optionally attach event listeners to the script
runningScript.on('close', () => console.log('Time to die...'))
runningScripts.push(runningScript); // Keep a reference to the script for later use
});
Communicating with forked scripts
Forking also has the added benefit that the parent script can receive events from the forked child processes as well as send back. A common example is for the parent script to kill its forked children.
runningScripts.forEach(runningScript => runningScript.kill());
For more available events and methods see the ChildProcess documentation
npm-run-all --parallel task1 task2
edit:
You need to have npm-run-all installed beforehand. Also check this page for other usage scenarios.
Quick Solution
In this case, I'd say the best bet If this script is for a private module intended to run only on *nix-based machines, you can use the control operator for forking processes, which looks like this: &
An example of doing this in a partial package.json file:
{
"name": "npm-scripts-forking-example",
"scripts": {
"bundle": "watchify -vd -p browserify-hmr index.js -o bundle.js",
"serve": "http-server -c 1 -a localhost",
"serve-bundle": "npm run bundle & npm run serve &"
}
You'd then execute them both in parallel via npm run serve-bundle. You can enhance the scripts to output the pids of the forked process to a file like so:
"serve-bundle": "npm run bundle & echo \"$!\" > build/bundle.pid && npm run serve & echo \"$!\" > build/serve.pid && npm run open-browser",
Google something like bash control operator for forking to learn more on how it works. I've also provided some further context regarding leveraging Unix techniques in Node projects below:
Further Context RE: Unix Tools & Node.js
If you're not on Windows, Unix tools/techniques often work well to achieve something with Node scripts because:
Much of Node.js lovingly imitates Unix principles
You're on *nix (incl. OS X) and NPM is using a shell anyway
Modules for system tasks in Nodeland are also often abstractions or approximations of Unix tools, from fs to streams.
step by step guide to run multiple parallel scripts with npm.
install npm-run-all package globally
npm i -g npm-run-all
Now install and save this package within project where your package.json exists
npm i npm-run-all --save-dev
Now modify scripts in package.json file this way
"scripts": {
"server": "live-server index.html",
"watch": "node-sass scss/style.scss --watch",
"all": "npm-run-all --parallel server watch"
},
now run this command
npm run all
more detail about this package in given link
npm-run-all
with installing npm install concurrently
"scripts": {
"start:build": "tsc -w",
"start:run": "nodemon build/index.js",
"start": "concurrently npm:start:*"
},
Use concurrently to run the commands in parallel with a shared output stream. To make it easy to tell which output is from which process, use the shortened command form, such as npm:wp-server. This causes concurrently to prefix each output line with its command name.
In package.json, your scripts section will look like this:
"scripts": {
"start": "concurrently \"npm:start-watch\" \"npm:wp-server\"",
"start-watch": "nodemon run-babel index.js",
"wp-server": "webpack-dev-server"
}
npm install npm-run-all --save-dev
package.json:
"scripts": {
"start-watch": "...",
"wp-server": "...",
"dev": "npm-run-all --parallel start-watch wp-server"
}
More info: https://github.com/mysticatea/npm-run-all/blob/master/docs/npm-run-all.md
In a package.json in the parent folder:
"dev": "(cd api && start npm run start) & (cd ../client && start npm run start)"
this work in windows
Just add this npm script to the package.json file in the root folder.
{
...
"scripts": {
...
"start": "react-scripts start", // or whatever else depends on your project
"dev": "(cd server && npm run start) & (cd ../client && npm run start)"
}
}
... but that will wait for start-watch to finish before running wp-server.
For that to work, you will have to use start on your command. Others have already illustrated but this is how it will work, your code below:
"dev": "npm run start-watch && npm run wp-server"
Should be :
"dev": " start npm run start-watch && start npm run wp-server"
What this will do is, it will open a separate instance for each command and process them concurrently, which shouldn't be an issue as far as your initial issue is concerned. Why do I say so? It's because these instances both open automatically while you run only 1 statement, which is your initial goal.
I ran into problems with & and |, which exit statuses and error throwing, respectively.
Other solutions want to run any task with a given name, like npm-run-all, which wasn't my use case.
So I created npm-run-parallel that runs npm scripts asynchronously and reports back when they're done.
So, for your scripts, it'd be:
npm-run-parallel wp-server start-watch
My solution is similar to Piittis', though I had some problems using Windows. So I had to validate for win32.
const { spawn } = require("child_process");
function logData(data) {
console.info(`stdout: ${data}`);
}
function runProcess(target) {
let command = "npm";
if (process.platform === "win32") {
command = "npm.cmd"; // I shit you not
}
const myProcess = spawn(command, ["run", target]); // npm run server
myProcess.stdout.on("data", logData);
myProcess.stderr.on("data", logData);
}
(() => {
runProcess("server"); // package json script
runProcess("client");
})();
This worked for me
{
"start-express": "tsc && nodemon dist/server/server.js",
"start-react": "react-scripts start",
"start-both": "npm -p -r run start-react && -p -r npm run start-express"
}
Both client and server are written in typescript.
The React app is created with create-react-app with the typescript template and is in the default src directory.
Express is in the server directory and the entry file is server.js
typescript code and transpiled into js and is put in the dist directory .
checkout my project for more info: https://github.com/nickjohngray/staticbackeditor
UPDATE:
calling npm run dev, to start things off
{"server": "tsc-watch --onSuccess \"node ./dist/server/index.js\"",
"start-server-dev": "npm run build-server-dev && node src/server/index.js",
"client": "webpack-dev-server --mode development --devtool inline-source-map --hot",
"dev": "concurrently \"npm run build-server-dev\" \"npm run server\" \"npm run client\""}
You can also use pre and post as prefixes on your specific script.
"scripts": {
"predev": "nodemon run-babel index.js &",
"dev": "webpack-dev-server"
}
And then run:
npm run dev
In my case I have two projects, one was UI and the other was API, and both have their own script in their respective package.json files.
So, here is what I did.
npm run --prefix react start& npm run --prefix express start&
Simple node script to get you going without too much hassle. Using readline to combine outputs so the lines don't get mangled.
const { spawn } = require('child_process');
const readline = require('readline');
[
spawn('npm', ['run', 'start-watch']),
spawn('npm', ['run', 'wp-server'])
].forEach(child => {
readline.createInterface({
input: child.stdout
}).on('line', console.log);
readline.createInterface({
input: child.stderr,
}).on('line', console.log);
});
I have been using npm-run-all for some time, but I never got along with it, because the output of the command in watch mode doesn't work well together. For example, if I start create-react-app and jest in watch mode, I will only be able to see the output from the last command I ran. So most of the time, I was running all my commands manually...
This is why, I implement my own lib, run-screen. It still very young project (from yesterday :p ) but it might be worth to look at it, in your case it would be:
run-screen "npm run start-watch" "npm run wp-server"
Then you press the numeric key 1 to see the output of wp-server and press 0 to see the output of start-watch.
A simple and native way for Windows CMD
"start /b npm run bg-task1 && start /b npm run bg-task2 && npm run main-task"
(start /b means start in the background)
I think the best way is to use npm-run-all as below:
1- npm install -g npm-run-all <--- will be installed globally
2- npm-run-all --parallel server client
How about a good old fashioned Makefile?
This allows you a lot of control including how you manage subshells, dependencies between scripts etc.
# run both scripts
start: server client
# start server and use & to background it
server:
npm run serve &
# start the client
client:
npm start
call this Makefile and then you can just type
make start to start everything up. Because the server command is actually running in a child process of the start command when you ctrl-C the server command will also stop - unlike if you just backgrounded it yourself at the shell.
Make also gives you command line completion, at least on the shell i'm using. Bonus - the first command will always run so you can actually just type make on it's own here.
I always throw a makefile into my projects, just so I can quickly scan later all the common commands and parameters for each project as I flip between them.
Using just shell scripting, on Linux.
"scripts": {
"cmd": "{ trap 'trap \" \" TERM; kill 0; wait' INT TERM; } && blocking1 & blocking2 & wait"
}
npm run cmd
and then
^C will kill children and wait for clean exit.
As you may need to add more and more to this scripts it will become messy and harder to use. What if you need some conditions to check, variables to use? So I suggest you to look at google/zx that allows to use js to create scripts.
Simple usage:
install zx: npm i -g zx
add package.json commands (optional, you can move everything to scripts):
"scripts": {
"dev": "zx ./scripts/dev.mjs", // run script
"build:dev": "tsc -w", // compile in watch mode
"build": "tsc", // compile
"start": "node dist/index.js", // run
"start:dev": "nodemon dist/index.js", // run in watch mode
},
create dev.mjs script file:
#!/usr/bin/env zx
await $`yarn build`; // prebuild if dist is empty
await Promise.all([$`yarn start:dev`, $`yarn build:dev`]); // run in parallel
Now every time you want to start a dev server you just run yarn dev or npm run dev.
It will first compile ts->js and then run typescrpt compiler and server in watch mode in parallel. When you change your ts file->it's will be recompiled by tsc->nodemon will restart the server.
Advanced programmatic usage
Load env variables, compile ts in watch mode and rerun server from dist on changes (dev.mjs):
#!/usr/bin/env zx
import nodemon from "nodemon";
import dotenv from "dotenv";
import path from "path";
import { fileURLToPath } from "url";
// load env variables
loadEnvVariables("../env/.env");
await Promise.all([
// compile in watch mode (will recompile on changes in .ts files)
$`tsc -w`,
// wait for tsc to compile for first time and rerun server on any changes (tsc emited .js files)
sleep(4000).then(() =>
nodemon({
script: "dist/index.js",
})
),
]);
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
function getDirname() {
return path.dirname(fileURLToPath(import.meta.url));
}
function loadEnvVariables(relativePath) {
const { error, parsed } = dotenv.config({
path: path.join(getDirname(), relativePath),
});
if (error) {
throw error;
}
return parsed;
}

Resources