我在MacOS,Node v12上并使用子进程(exec / spawn / execSync / spawnSync)执行可返回8192个以上字符的shell命令。但是,回到调用子进程的nodeJS方法中,我最多只能得到8192个字符,仅此而已。 (8192 seems to be the default pool size for a buffer)。

我尝试将“选项”中的maxBuffer大小增加到大于8192的任何值,但这不会影响任何内容。

我也尝试过使用exec,spawn,execSync和spawnSync运行相同的命令,它们的行为方式都相同。结果相同。

当我跑步时:

 exec(shellCommand, { encoding: "buffer", maxBuffer: 16384 }, (error, stdout, stderr) => {
     console.log('stdout--> length: ', stdout.length, '<--->', stdout)
 });


我得到:

stdout--> length: 8192 <---> <Buffer 7b 22 72 65 73 75 6c 74 22 3a 5b 7b 22 70 72 6f 6a 65 63 74 4e 61 6d 65 22 3a 22 73 65 65 64 73 22 2c 22 74 65 6d 70 6c 61 74 65 4e 61 6d 65 22 3a 22 ... 8142 more bytes>


我知道返回的数据大于8192,因为当我在shell中运行shell命令并检查其长度是否大于8192时。

而且,这是令人费解的,当我将子进程的stdio选项设置为“继承”时,例如:

execSync(shellCommand, { encoding: "buffer", stdio:"inherit" });


(这表示使用parents stdout,在我的情况下是NodeJS的控制台)

我在运行NodeJS的控制台中看到了完整的响应。

我在github上也读过类似的问题,但并没有真正帮助。

如何在NodeJS中执行Shell命令并获得完整响应?

最佳答案

尝试这个 :

const { spawn } = require('child_process');
const cmd = spawn('command', ['arg1', 'arg2']);
let bufferArray= []
/*cmd.stdout.setEncoding('utf8'); sets encdoing
 defualt encoding is buffer
*/
cmd.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
  bufferArray.push(data)
});

cmd.stderr.on('data', (data) => {
  console.error(`stderr: ${data}`);
});

cmd.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
  let dataBuffer =  Buffer.concate(bufferArray];
  console.log(dataBuffer.toString())
});


这可能很有用:Node.js spawn child process and get terminal output live

08-26 13:21