How to intercept and save to a variable the output

2019-08-09 10:34发布

问题:

I have this script that properly run synchronously the ls command and output the result to the terminal. How can I intercept the result and save it to a variable?

const cp = require('child_process');
const result = cp.spawnSync(
    'ls',
    ['-l', '/usr'],
    { stdio: [process.stdin, process.stdout, process.stdout] }
);

If I try this, as suggested by https://stackoverflow.com/a/30617874/693271

result.stdout.on('data', function (chunk) {
    console.log(chunk);
});

I get

result.stdout.on('data', function (chunk) {
              ^
TypeError: Cannot read property 'on' of null

The difference is that is about spawnSync and not about spawn

回答1:

By looking at the docs we can see that the result of spawnSync returns an object containing a key called stdout, which is a Buffer. You do not have to listen to events since you're calling the synchronous version of the spawn - the process will wait for the command to finish executing before resuming and then returns the result.

So in your case, the result of your ls -l /usr command can be read with result.stdout.toString(). You also need to keep the default config for stdio in the options.