0

I am executing a shell command programatically through Node.js and the result is true... literally <string> true, but I cannot compare it neither to boolean nor to string.

const exec = require('child_process').exec;

exec('docker inspect -f {{.State.Running}} service-redis', (err, stdout, stderr) => {
   // here stdout has value "true"
   console.log(typeof stdout) // returns "string"
   console.log(stdout == 'true') // returns false
   console.log(stdout == true) // returns false
});

I tried converting stdout.toString() just in case, but the result is the same. I am confused. Any ideas?

Milkncookiez
  • 6,817
  • 10
  • 57
  • 96

1 Answers1

4

You need to trim the string, as it has invisible whitespace at the end in the form of a newline.

const exec = require('child_process').exec;

exec('docker inspect -f {{.State.Running}} service-redis', (err, stdout, stderr) => {
    // here stdout has value "true"
    console.log(stdout.trimRight() === 'true')
});

Note that the trailing newline is not Node doing anything weird. It is generally the case that programs append a newline to their console output, particularly if a human will be looking at it. In fact, this is one of the things console.log() does for you.

Imagine using your terminal if the programs you use every day (ls, git, ...) terminated their output without a newline. Your prompt (the marker before where you type, e.g. $) would be crowded on the same line as the output from the last program. Yuck!

Even files usually end with a newline, as this makes it easier to concatenate data together from various sources (e.g. log files) and work with UNIX tools. There is also a widely held practice to have your code editor enforce this for you. In short, you will see this all over the place.

The childProcess.exec() method does not make any assumptions about these newline conventions, it is too low-level for that, and so it keeps them in place. Issues of tiny modules aside, you could easily create an abstraction on top of exec() that handles trimming for you.

Community
  • 1
  • 1
Seth Holladay
  • 8,951
  • 3
  • 34
  • 43
  • Now that you mentioned it, I noticed that there's always a blank line printed after the value of `stdout`, so there's a `\n` at the end. Tnx! – Milkncookiez Dec 27 '16 at 15:34
  • 1
    No problem @Milkncookiez. I added some background and context that might be of interest to you. – Seth Holladay Dec 27 '16 at 16:46