Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grunt task: start mongod if not running

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

like image 859
Max Bates Avatar asked Jan 12 '23 15:01

Max Bates


1 Answers

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!

like image 97
Max Bates Avatar answered Jan 21 '23 00:01

Max Bates