【问题标题】:How to execute a mongoDB shell script via Node.js?如何通过 Node.js 执行 mongoDB shell 脚本?
【发布时间】:2020-03-30 18:56:44
【问题描述】:

我正在做我的课堂项目,我想在其中演示 mongoDB 分片的使用。我正在使用 mongoDB node.js 本机驱动程序。我知道这个驱动程序中没有分片功能。所以,我必须编写 shell 脚本来进行分片。那么,是否可以像这样以某种方式做到这一点:

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

【问题讨论】:

  • 试试一些代码,如果你有问题,把它贴在这里。有人可以为您发布答案,但您不会学习(这是上课的重点)

标签: node.js mongodb shell sharding


【解决方案1】:

鉴于您已经有一个 shell 脚本,为什么不通过 Child Process 模块执行它。只需使用以下函数来运行您拥有的脚本。

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

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

【讨论】:

    【解决方案2】:

    为什么不考虑使用 npm run 脚本? 如果您希望脚本独立运行,请将带有 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 将在您进一步构建时显示脚本的进度。 希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2013-04-17
      • 2011-10-23
      • 2014-10-06
      • 2020-05-31
      • 1970-01-01
      • 2011-06-17
      • 1970-01-01
      • 2011-08-16
      • 1970-01-01
      相关资源
      最近更新 更多