1

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

2
  • Please search before posting. More about searching here. Commented May 28, 2019 at 13:29
  • I found stuff for spawn but not for spawnSync yet. Keep searching Commented May 28, 2019 at 13:49

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I am getting Cannot read property 'toString' of null, I wonder what I am doing wrong...
I tried your code, and it works if you don't specify any custom stdio config (removed the options altogether)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.