以编程方式停止 MongoDB

Programmatically stopping MongoDB

我正在使用 Node.JS、Electron 开发一个应用程序。此应用程序将 运行 它自己的 MongoDB 实例。 Mongo 的启动正在使用以下代码:

child = childProcess.exec(`mongod --dbpath ${appConfig.dbConfigPath}`);

但是,当用户退出程序时,我想停止mongo。我尝试了以下内容,全部取自 MongoDB Documentation

child = childProcess.exec('mongod --shutdown');

child = childProcess.exec(`kill -2 ${child.pid}`);

然而这些都没有关闭进程。

此应用程序正在 windows 平台上开发到 运行。

为清楚起见,这是我的应用程序配置文件。 init() 函数是从我的 main.js 中执行的。 shutdown() 在 windowMain.on('close').

中执行

calibration.js

'use strict';

const childProcess = require('child_process');

const fileUtils = require('./lib/utils/fileUtils');
const appConfig = require('./config/appConfig');

let child;

class Calibration {
    constructor() {}

    init() {
        createAppConfigDir();
        createAppDataDir();
        startMongo();
    }

    shutdown() {
        shutdownMongo();
    }
}

function createAppConfigDir() {
    fileUtils.createDirSync(appConfig.appConfigDir);
}

function createAppDataDir() {
    fileUtils.createDirSync(appConfig.dbConfigPath);
}

function startMongo() {
    child = childProcess.exec(`mongod --dbpath ${appConfig.dbConfigPath}`);
    console.log(child.pid);
}

function shutdownMongo() {
    console.log('inside shutdownMongo');
    //This is where I want to shutdown Mongo
}

module.exports = new Calibration();

main.js

'use strict'

const { app, BrowserWindow, crashReporter, ipcMain: ipc } = require('electron');
const path = require('path');

const appCalibration = require('../calibration');

appCalibration.init();

const appConfig = require('../config/appConfig');

let mainWindow = null;

ipc.on('set-title', (event, title) => {
    mainWindow.setTitle(title || appconfig.name);
})

ipc.on('quit', () => {
    app.quit();
})

// Quit when all windows are closed.
app.on('window-all-closed', function() {
    if (process.platform != 'darwin') {
        app.quit();
    }
});

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {

    // Create the browser window.
    mainWindow = new BrowserWindow({ center: true });

    mainWindow.maximize();

    mainWindow.setMinimumSize(770, 400);

    mainWindow.loadURL(path.join(`file://${__dirname}`, '../ui/index.html'));

    mainWindow.on('close', () => {
        console.log('Inside quit')
        appCalibration.shutdown();
        app.quit();
    });

    mainWindow.on('closed', function() {
        mainWindow = null;
    });
});

非常感谢任何帮助。

您可以使用 Ipc 通过您的 js 文件发送订单。

在你定义电子的 main.js 中,你可以这样写:

ipcMain.on("shutDownDatabase", function (event, content) {
    // shutdown operations.
});

然后在您的应用程序代码的某些部分,您可以放置​​一个这样的函数:

function sendShutdownOrder (content){
   var ipcRenderer = require("electron").ipcRenderer;
   // the content can be a parameter or whatever you want that should be required for the operation.
   ipcRenderer.send("shutDownDatabase", content);
}

另外我认为你可以使用 Electron 的事件来关闭你的数据库,它会监听你启动 electron 时创建的 mainWindow 的事件

    mainWindow.on('closed', function () {
        // here you command to shutdowm your data base.
        mainWindow = null;
    });

有关 IPC 的更多信息,请参阅 here and information about the events of your window here

在 Paulo Galdo Sandoval 的建议下,我得以实现它。但是,我需要从 Windows 任务管理器获取 mongod 的 PID。为此,我将以下功能添加到应用程序配置 js 文件

function getTaskList() {
    let pgm = 'mongod';

    exec('tasklist', function(err, stdout, stderr) {
        var lines = stdout.toString().split('\n');
        var results = new Array();
        lines.forEach(function(line) {
            var parts = line.split('=');
            parts.forEach(function(items) {
                if (items.toString().indexOf(pgm) > -1) {
                    taskList.push(items.toString().replace(/\s+/g, '|').split('|')[1])
                }
            });
        });
    });
}

我还声明了一个数组变量来放置定位的PID。然后我更新了我的关闭函数

function shutdownMongo() {
    var pgm = 'mongod';

    console.log('inside shutdownMongo');

    taskList.forEach(function(item) {
        console.log('Killing process ' + item);
        process.kill(item);
    });
}

有了这个,我现在可以在我的应用程序启动和关闭时启动和停止 Mongo。

谢谢大家