如何通过Node.js执行mongoDB shell脚本?

问题描述 投票:1回答:2

我正在上我的班级项目,我想在其中演示mongoDB分片的用法。我正在使用mongoDB node.js本机驱动程序。我知道此驱动程序中没有分片功能。因此,我必须编写shell脚本来进行分片。因此,是否可以这样进行:

node myfile.js(执行我的shell脚本并运行我的代码)

node.js mongodb shell sharding
2个回答
0
投票

鉴于您已经具有Shell脚本,为什么不通过Child Process模块执行该脚本。只需使用以下功能即可运行您拥有的脚本。

child_process.execFileSync(file[, args][, options])

请注意,脚本应具有运行权限(否则请使用chmod a+x script


0
投票

您为什么不考虑使用npm运行脚本?如果您希望脚本独立运行,请将带有test / start或同时包含两者的脚本添加到包json中,

"scripts": {
    "test": "node mytestfile.js",
    "start": "node ./myfile --param1 --param2"
  },

run npm run testnpm run start,它们可以执行脚本文件。这样,您甚至可以将参数传递给脚本。

或优雅的child_process方法,

const { exec } = require("child_process");
exec("node myfile.js", (error, stdout, stderr) => {
    if (error) {
        console.log(`error: ${error.message}`);
        return;
    }
    if (stderr) {
        console.log(`stderr: ${stderr}`);
        return;
    }
    console.log(`stdout: ${stdout}`);
});

stderr和stdout将在您进一步构建时显示脚本的进度。希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.