grunt任务:如果没有运行,启动mongod

Max*_*tes 4 javascript mongodb gruntjs

mongod如果服务器尚未运行,我想编写一个grunt任务来启动进程.我需要运行一个mongod进程,但是还需要grunt-watch在以后的任务流程中工作.

这个问题解释了如何启动mongod使用grunt-shell...接受的答案是阻止,并且异步版本将生成一个新的服务器,即使存在.

是否有一种方法(例如shell脚本)只有在没有运行的情况下启动mongod,而不会阻止其余的grunt任务流?

谢谢

Max*_*tes 6

这是一个更清洁的版本

将其存储startMongoIfNotRunning.sh在与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;
Run Code Online (Sandbox Code Playgroud)

在你的Gruntfile中:

shell: {
    mongo: {
        command: "sh startMongoIfNotRunning.sh",
        options: {
            async: true
        }
    },
}
Run Code Online (Sandbox Code Playgroud)

编辑 - 下面的原始版本

好的 - 我觉得这个工作正常......

创建一个shell脚本,如果它没有运行将启动mongod ...将它保存在某个地方,可能在你的项目中.我把它命名为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
Run Code Online (Sandbox Code Playgroud)

您可能必须使其可执行: chmod +x path/to/script/startMongoIfNotRunning.sh

安装grunt-shell-spawn: npm install grunt-shell-spawn --save-dev

然后在你的Gruntfile中添加:

shell: {
      mongo: {
          command: "exec path/to/script/startMongoIfNotRunning.sh",
          options: {
              async: true
          }
      },
}
Run Code Online (Sandbox Code Playgroud)

(如果你使用的是yeoman,使用<%= yeoman.app %>不起作用,因为这些路径是相对于整个项目的,所以你得到的东西就像'app'而不是脚本的整个路径.我相信你可以让它工作,我只是不知道如何获得路径)

如果您只是执行任务grunt shell:mongomongod将启动但我无法使用它关闭它grunt shell:mongo:kill.但是,假设您稍后使用阻止任务(我正在使用watch),那么当您结束该任务时它应该自动被杀死.

希望这有助于某人!