nodeJS中调用exe文件

3 篇文章 0 订阅

背景

由于不同语言各有优势,所以有时候会用不同的语言去写不同的脚本,这次写的软件中涉及到爬虫的部分用python写的,主程序用electron+vue的方式写的,所以使用了child_process来调用python打包的exe

方法

node中有一个child_process可以用来创建子进程,这里我就用该功能进行exe的调用,具体方法如下

const cp = require('child_process')
let child = cp.spawn('./exename.exe',[param])

child_process有多种调用方法,详情见:node文档的child_process部分

异步进程的创建
在 Windows 上衍生 .bat 和 .cmd 文件
	child_process.exec(command[, options][, callback])
	child_process.execFile(file[, args][, options][, callback])
	child_process.fork(modulePath[, args][, options])
	child_process.spawn(command[, args][, options])
	options.detached
	options.stdio
同步进程的创建
	child_process.execFileSync(file[, args][, options])
	child_process.execSync(command[, options])
	child_process.spawnSync(command[, args][, options])

常用的主要事件如close等,可以直接用on监听如:

child.on('close',(res)=>{})

监听返回值,返回值要进行fromCharCode解码

child.stdout.on('data',(data)=>{
   for (var i = 0; i < data.length; i++) {
    exeMsg += String.fromCharCode(data[i]);
 }

不过对于从子进程中获取实时返回值,我多次尝试无效,后来只能采用临时文件的方式进行处理,可以在如下的案例中看出

案例

在我的案例中

const cp = require('child_process')
 let child = cp.spawn('./e5/e5.exe',[file])
 this.int=setInterval(that.readProcess,300);
 child.on('close', (stderr) => {
   that.proStr="就绪"
   fs.writeFile('pr.xw', "...", function(err){});
   clearInterval(that.int)
   that.ReadData()
 })
  // child.stderr.on('data', (stderr) => {
        //   console.log(stderr)
        // })
        // child.stdout.on('data',(data)=>{
        //   for (var i = 0; i < data.length; i++) {
        //     exeMsg += String.fromCharCode(data[i]);
        //   }

由于实时获取返回值的尝试未果,使用临时文件和定时任务来获取信息,这个方式有很多问题,但是目前项目比较紧,就先将就着用这个方式了。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值