I want to write a grunt task to start the process mongod
if the server is not already running. I need a mongod process running, but also need grunt-watch to work later in the task flow.
This question explains how to start mongod using grunt-shell
... the accepted answer is blocking, and the async version will spawn a new server even if one exists.
Is there a way (e.g. shell script) to start mongod only if it is not running, without blocking the rest of the grunt task flow?
Thanks
Here's a cleaner version
Store this as startMongoIfNotRunning.sh
in same location as Gruntfile:
# this script checks if the mongod is running, starts it if not
if pgrep -q mongod; then
echo running;
else
mongod;
fi
exit 0;
And in your Gruntfile:
shell: {
mongo: {
command: "sh startMongoIfNotRunning.sh",
options: {
async: true
}
},
}
Edit - original version below
Ok - I think this is working properly...
create a shell script which will start mongod if it's not running... save it somewhere, probably in your project. I named it startMongoIfNotRunning.sh :
# this script checks if the mongod is running, starts it if not
`ps -A | grep -q '[m]ongod'`
if [ "$?" -eq "0" ]; then
echo "running"
else
mongod
fi
You may have to make it executable: chmod +x path/to/script/startMongoIfNotRunning.sh
Install grunt-shell-spawn : npm install grunt-shell-spawn --save-dev
Then in your Gruntfile add this:
shell: {
mongo: {
command: "exec path/to/script/startMongoIfNotRunning.sh",
options: {
async: true
}
},
}
(If you're using yeoman, using <%= yeoman.app %>
didn't work because those paths are relative to the whole project, so you get something like 'app' instead of the whole path to the script. I'm sure you could get it working, I'm just not aware how to get the path to )
If you just execute the task grunt shell:mongo
mongod will start but I wasn't able to close it using grunt shell:mongo:kill
. However, assuming you're using a blocking task later (I'm using watch
) then it should automatically be killed when you end that task.
Hope this helps someone!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With