【发布时间】:2018-05-06 08:42:03
【问题描述】:
我将 mongodb 作为 node.js 的子进程运行,并且需要按需关闭和重新启动。使用 Child_Process.kill("SIGINT") 似乎是正确的方法,但它使 mongo 处于混乱状态,直到修复(或锁定文件被删除)才会重新启动。有没有更好的方法来做到这一点?
谢谢, 安迪
【问题讨论】:
我将 mongodb 作为 node.js 的子进程运行,并且需要按需关闭和重新启动。使用 Child_Process.kill("SIGINT") 似乎是正确的方法,但它使 mongo 处于混乱状态,直到修复(或锁定文件被删除)才会重新启动。有没有更好的方法来做到这一点?
谢谢, 安迪
【问题讨论】:
执行kill("SIGINT") 会导致数据库在不执行所需步骤的情况下关闭,并可能导致数据文件损坏。所以我不建议这样做。
停止数据库的正常方法是从 mongodb shell 发送命令 { "shutdown" : 1 } 或 db.shutdownServer(),但我不知道如何从 node.js 驱动程序执行此操作。
【讨论】:
你可以试试这样的:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:27017/admin", function(err, db) {
if (err) {
console.log('mongodb is not running');
process.exit(0);
}
else {
db.command({
shutdown : 1
}, function(err, result) {
console.log('shutting down mongodb - ', err.message);
process.exit(0);
});
}
});
【讨论】:
你可以在 mac 上使用 nodeJS 结束一个 mongodb 进程
1) 将下面的脚本保存到 script.js
'use strict'
const exec = require('child_process').execSync;
function killport(port) {
var processId = null
try {
processId = exec(`lsof -t -i:${port}`);
} catch (e) {
console.log("could not catch");
}
if (processId !== null) { // if exists kill
try{
if(exec(`kill ${processId}`)){
console.log("closed");
}
} catch(e){
console.log("error executing");
}
}
}
killport(27017);
2) 运行节点脚本.js
【讨论】: