windows下node.js调用bat

node.js调用bat需要用到Child Processes模块

因为bat是文件,所以需要使用execFile方法

 

如果指定了cwd,它会切换bat执行的目录,类似cd的功能,如果未指定默认为当前调用程序的目录。如果bat有输出错误,例如创建指定的文件/目录已经存在时,会返回一个错误信息时,调用bat会得到一个相关的错误信息:Error {killed: false, code: 1, signal: null}

process.execFile(url, [1, 2], {cwd:'D:/'}, function(error, stdout, stderr) {
console.log(error);
console.log(stdout);
alert(1);
});

 

如果只指定了盘符,而非一个可访问的路径时,会得到Error: spawn EBADF

process.execFile(url, [1, 2], {cwd:'D'}, function(error, stdout, stderr) {
console.log(error);
console.log(stdout);
alert(1);
});
 
输出:Error {code: "EBADF", errno: "EBADF", syscall: "spawn"}
 
二种方式可以得到调用bat的返回结果,一种是直接回调函数里获取stdout的值,还有一种是监听子进程的data事件
var child_proc = process.execFile(url, [1, 2], {cwd:dirName}, function(error, stdout, stderr) {
console.log(error);
console.log(stdout);
});

child_proc.stdout.on('data', function(data) {
console.log(data);
});
 
假设bat的文件内容是创建三个目录,其中二个目录是通过参数传递进去的(上面代码中的数组[1, 2],其中1、2就是参数)
@echo off

echo hahaniu~~~

mkdir %1
mkdir %2
mkdir aa

执行上面的代码后,会在指定的目录下(也就是代码中cwd参数的值)创建相应的目录,其中stdout将得到“hahaniu~~~”的输出


 
 
除了execFile方法外,还有exec方法亦能达到目的。用exec分解调用的文件功能,如下面的示例(创建一个目录)
process.exec("mkdir " + (new Date().getTime()), function(error, stdout, stderr) {

});


 
 
如果node.js想查询注册表或者其它信息,可以直接像在dos下输入命令一下,例如查询winrar安装目录
process.exec("reg query HKEY_CLASSES_ROOT\\WinRAR\\shell\\open\\command /ve", function(error, stdout, stderr) {
var path = stdout.match(/(\"[^\"]+\")/)[1]

console.log(path);
});

 
 
 
自此,以前用hta的工具都可以用node-webkit替代了
 
【参考资料】
posted @ 2014-01-17 15:59  meteoric_cry  阅读(15459)  评论(3编辑  收藏  举报