关于electron spawn回调中返回值过长出现的问题以及解决方案

child_process

当我们在使用electron框架进行编程的时候,我们可能会使用child_process这个库进行命令行的使用,官方文档的说明是:

The child_process module provides the ability to spawn child processes in a manner that is similar, but not identical, to popen(3).This capability is primarily provided by the child_process.spawn() function

也就是说它会生成一个子进程进行一些操作。一般我们回调使用的是的exec(),execfile(),spawn()这些函数进行操作,其实还有execSync(),execfileSync(),spawnSync()这些方法进行同步的调用。其实这些方法都是基于spawn方法。

同时文档还提醒:

By default, pipes for stdinstdout, and stderr are established between the parent Node.js process and the spawned child. These pipes have limited (and platform-specific) capacity. If the child process writes to stdout in excess of that limit without the output being captured, the child process will block waiting for the pipe buffer to accept more data. This is identical to the behavior of pipes in the shell. Use the { stdio: 'ignore' } option if the output will not be consumed.

默认情况下,在父Node.js进程与生成的子进程之间建立了stdin,stdout和stderr的管道。根据平台的不同,这些管道可以传输的数据量是不同的,但都是有限的。

The child_process.spawn() method spawns the child process asynchronously, without blocking the Node.js event loop. The child_process.spawnSync() function provides equivalent functionality in a synchronous manner that blocks the event loop until the spawned process either exits or is terminated.

 spawn和spawnSync两个方法,前者不会造成阻塞,而后者则会阻塞至所有返回值都接收到了。

遇到的问题

在实际使用中我们通常会使用spawn()方法,或者exec()方法。在我的实际使用中,由于某些无法修改的问题,调用.exe文件进行返回的值特别长,远远超出了exec()方法的限制,只能使用spawn()方法进行回调,这个时候就出现了新的问题。

在windows平台下使用的时候,我对返回的json格式数据进行JSON.parse()解析,解析成功,但是会有报错,好像管道返回了两次,一次是所有数据,一次是空值,我看运行成功了就没管了。

但是在linux平台在使用时,我使用同样的方法进行解析报错了,json格式出了错,log一下看到回调spawn返回了64次,每次都是数据的其中一段,我想大概就是文档中提到的不同平台传输数据有限的问题。这个问题似乎无解,因为运行时我也不知道会返回几次结果,也没法把回调的返回值取出来,除非保存在localstorage,但是每次都要拼接、保存太浪费资源。

解决方法

这里实在没办法只能使用spawnSync()这个方法的接口了,使用同步的方法,当所有返回值都接收到了之后再返回。效率似乎低了一些,没测试,但是勉强能用吧。

大家用的时候要注意:

spawn的返回值: 

Returns: <ChildProcess>

spawnSync的返回值:

Returns: <Object>

  • pid <number> Pid of the child process.
  • output <Array> Array of results from stdio output.
  • stdout <Buffer> | <string> The contents of output[1].
  • stderr <Buffer> | <string> The contents of output[2].
  • status <number> | <null> The exit code of the subprocess, or null if the subprocess terminated due to a signal.
  • signal <string> | <null> The signal used to kill the subprocess, or null if the subprocess did not terminate due to a signal.
  • error <Error> The error object if the child process failed or timed out.

调用的时候需要注意,另外返回的buffer格式可以使用.toString()转换成str格式。 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值