如何从节点应用程序执行命令

How to execute command from node application

本文关键字:执行 命令 应用程序 节点      更新时间:2023-09-26

我需要从我的node JS应用程序调用CMD命令,这可能吗?

我尝试以下(POC),我得到错误

var express = require('express');
var app = express();
app.get('/', function (req, res) {
    function cmd_exec(cmd, args, cb_stdout, cb_end) {
        var spawn = require('child_process').spawn,
            child = spawn(cmd, args),
            me = this;
        me.exit = 0;  // Send a cb to set 1 when cmd exits
        child.stdout.on('data', function (data) {
            cb_stdout(me, data)
        });
        child.stdout.on('end', function () {
            cb_end(me)
        });
    }
    foo = new cmd_exec('npm', 'install glob --save',
        function (me, data) {
            me.stdout += data.toString();
        },
        function (me) {
            me.exit = 1;
        }
    );
    setTimeout(
        // wait 0.25 seconds and print the output
        log_console,
        250);

    function log_console() {
        console.log(foo.stdout);
    }
    res.send("Hello world");
});

我在以下链接

中看到了这段代码

node.js shell命令执行

错误是:TypeError:参数选项的值不正确行child = spawn(cmd, args),

目前我只是使用npm install命令(只是为了测试),但我可以执行和运行的任何其他命令将是足够的

在执行终端命令时,有两部分:命令和参数。在您的示例中,命令是npm,参数是其后的所有内容。

cmd_exec('npm', ['install', 'glob', '--save'],