从nodejs执行批处理文件

时间:2023-01-19 18:51:42

Would it be possible to run a batch file from a nodejs application?

是否可以从nodejs应用程序运行批处理文件?

After googling for some time we can use child_process to execute the commands. Tried the same module but without success.

在谷歌搜索一段时间后,我们可以使用child_process来执行命令。尝试了相同的模块但没有成功。

Could somebody guide me?

有人可以指导我吗?

3 个解决方案

#1


8  

This creates a NodeJS module with a single function named exec() to execute batch scripts.

这将创建一个NodeJS模块,其中包含一个名为exec()的函数来执行批处理脚本。

var exec = require('child_process').exec,
    path = require('path'),
    os   = require('os');
    fs   = require('fs');

// HACK: to make our calls to exec() testable,
// support using a mock shell instead of a real shell
var shell = process.env.SHELL || 'sh';

// support for Win32 outside Cygwin
if (os.platform() === 'win32' && process.env.SHELL === undefined) { 
  shell = process.env.COMSPEC || 'cmd.exe';
}

// Merges the current environment variables and custom params for the environment used by child_process.exec()
function createEnv(params) {
    var env = {};
    var item;

    for (item in process.env) {
        env[item] = process.env[item];
    }

    for(item in params) {
        env[item] = params[item];
    }

    return env;
}

// scriptFile must be a full path to a shell script
exports.exec = function (scriptFile, workingDirectory, environment, callback) {
    var cmd;

    if (!workingDirectory) {
        callback(new Error('workingDirectory cannot be null'), null, null);
    }

    if (!fs.existsSync(workingDirectory)) {
        callback(new Error('workingDirectory path not found - "' + workingDirectory + '"'), null, null);
    }

    if (scriptFile === null) {
        callback(new Error('scriptFile cannot be null'), null, null);
    }

    if (!fs.existsSync(scriptFile)) {
        callback(new Error('scriptFile file not found - "' + scriptFile + '"'), null, null);
    }

    // transform windows backslashes to forward slashes for use in cygwin on windows
    if (path.sep === '\\') {
        scriptFile = scriptFile.replace(/\\/g, '/');
    }

    // TODO: consider building the command line using a shell with the -c argument to run a command and exit
    cmd = '"' + shell + '" "' + scriptFile + '"';

    // execute script within given project workspace
    exec(cmd,
         {
            cwd: workingDirectory,
            env: createEnv(environment)
         },
        function (error, stdout, stderr) {
            // TODO any optional processing before invoking the callback

            callback(error, stdout, stderr);
        }
    );
};

#2


2  

I have found the solution for it.. and its works fine for me. This opens up a new command window and runs my main node JS in child process. You need not give full path of cmd.exe. I was making that mistake.

我找到了它的解决方案..它的工作对我来说很好。这将打开一个新的命令窗口,并在子进程中运行我的主节点JS。您无需提供cmd.exe的完整路径。我犯了那个错误。

var spawn = require('child_process').spawn,
ls    = spawn('cmd.exe', ['/c', 'startemspbackend.bat']);

ls.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});

ls.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});

ls.on('exit', function (code) {
console.log('child process exited with code ' + code);
});

#3


0  

An easier way I know for executing that is the following code :

我知道执行的一种更简单的方法是以下代码:

function Process() {
    const process = require('child_process');   
    var ls = process.spawn('script.bat');
    ls.stdout.on('data', function (data) {
      console.log(data);
    });
    ls.stderr.on('data', function (data) {
      console.log(data);
    });
    ls.on('close', function (code) {
       if (code == 0)
            console.log('Stop');
       else
            console.log('Start');
    });
};

Process();

#1


8  

This creates a NodeJS module with a single function named exec() to execute batch scripts.

这将创建一个NodeJS模块,其中包含一个名为exec()的函数来执行批处理脚本。

var exec = require('child_process').exec,
    path = require('path'),
    os   = require('os');
    fs   = require('fs');

// HACK: to make our calls to exec() testable,
// support using a mock shell instead of a real shell
var shell = process.env.SHELL || 'sh';

// support for Win32 outside Cygwin
if (os.platform() === 'win32' && process.env.SHELL === undefined) { 
  shell = process.env.COMSPEC || 'cmd.exe';
}

// Merges the current environment variables and custom params for the environment used by child_process.exec()
function createEnv(params) {
    var env = {};
    var item;

    for (item in process.env) {
        env[item] = process.env[item];
    }

    for(item in params) {
        env[item] = params[item];
    }

    return env;
}

// scriptFile must be a full path to a shell script
exports.exec = function (scriptFile, workingDirectory, environment, callback) {
    var cmd;

    if (!workingDirectory) {
        callback(new Error('workingDirectory cannot be null'), null, null);
    }

    if (!fs.existsSync(workingDirectory)) {
        callback(new Error('workingDirectory path not found - "' + workingDirectory + '"'), null, null);
    }

    if (scriptFile === null) {
        callback(new Error('scriptFile cannot be null'), null, null);
    }

    if (!fs.existsSync(scriptFile)) {
        callback(new Error('scriptFile file not found - "' + scriptFile + '"'), null, null);
    }

    // transform windows backslashes to forward slashes for use in cygwin on windows
    if (path.sep === '\\') {
        scriptFile = scriptFile.replace(/\\/g, '/');
    }

    // TODO: consider building the command line using a shell with the -c argument to run a command and exit
    cmd = '"' + shell + '" "' + scriptFile + '"';

    // execute script within given project workspace
    exec(cmd,
         {
            cwd: workingDirectory,
            env: createEnv(environment)
         },
        function (error, stdout, stderr) {
            // TODO any optional processing before invoking the callback

            callback(error, stdout, stderr);
        }
    );
};

#2


2  

I have found the solution for it.. and its works fine for me. This opens up a new command window and runs my main node JS in child process. You need not give full path of cmd.exe. I was making that mistake.

我找到了它的解决方案..它的工作对我来说很好。这将打开一个新的命令窗口,并在子进程中运行我的主节点JS。您无需提供cmd.exe的完整路径。我犯了那个错误。

var spawn = require('child_process').spawn,
ls    = spawn('cmd.exe', ['/c', 'startemspbackend.bat']);

ls.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});

ls.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});

ls.on('exit', function (code) {
console.log('child process exited with code ' + code);
});

#3


0  

An easier way I know for executing that is the following code :

我知道执行的一种更简单的方法是以下代码:

function Process() {
    const process = require('child_process');   
    var ls = process.spawn('script.bat');
    ls.stdout.on('data', function (data) {
      console.log(data);
    });
    ls.stderr.on('data', function (data) {
      console.log(data);
    });
    ls.on('close', function (code) {
       if (code == 0)
            console.log('Stop');
       else
            console.log('Start');
    });
};

Process();