關於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格式。 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章