I've encountered this problem before while setting up npm scripts, and I haven't been able to find a solution yet. I'm hoping to make the solution compatible with both Mac and Windows environments.
I'm working on splitting up the logic of my npm scripts into smaller scripts that can interact with each other. This, combined with variables, would make the scripts more manageable and readable for other developers.
However, I'm struggling to use the result of one npm script in another. Since I'm not a bash expert, I'm seeking assistance here.
My current goal is to create a script that easily launches a docker (virtual) environment.
In the package.json file:
...
"config": {
"docker": {
"container": "docker-test"
}
},
"scripts": {
"container_run": "docker run -d -p 80:80 $npm_package_config_docker_container",
"container_running": "docker inspect -f {{.State.Running}} $npm_package_config_docker_container || echo 'false'",
"container_stop": "docker stop $npm_package_config_docker_container && docker rm $npm_package_config_docker_container",
"start": "???"
}
Here, I have a variable storing the name of the docker container to be run:
$npm_package_config_docker_container
.
When I execute npm run container_running
, it returns true if the container is running, or throws an error if the container doesn't exist, echoing 'false'.
Now, for the start script, I want it to check if the container is running. If it is, stop the container, then start a new one. If it's not running, just start a new one. Something like this:
"start": "if [ container_running == 'true' ]; then container_stop && container_run; else container_run; fi"
How can I achieve this? And as a bonus question, can it be done in a way that works on both Mac and Windows?
Any assistance would be greatly appreciated!