DEV Community

Penn
Penn

Posted on

simluate `&&` and `||` by using Nodejs

In the last article I expound how to run two Nodejs Modules in one without shell. The secret is child process offered by Nodejs iteself. Today I will cover other two different types with it that is to simulate && and || as shell.

Found a great explaination of && and || about shell.

&& strings commands together. Successive commands only execute if preceding ones succeed.
Similarly, || will allow the successive command to execute if the preceding fails.

The signal that shell depends on to determ if the commands succeed ends or not is the exit code.

The exit code

The exit code is the code that returned from your program. In the world of NodeJS, we us process.exit to exit and set a proper code for exit. e.g.

// exit without error
process.exit(0)

// exit with errors
process.exit(1)
Enter fullscreen mode Exit fullscreen mode

In general, 0 used as a success code, and others for anything else. We usually don't need to set the exit code explictly as the above script, NodeJS handles properly when the program exits.

Exit code of child process

The child process will emits exit event with the code as the data after it ends. And from the main process we can use the following script to inspect the code and make the following actions such as execute another script or not.

childprocess.on('exit', (code) => {
  // inspect the code and operate as "&&" or "||"
})
Enter fullscreen mode Exit fullscreen mode

So here we go

const fork = require('child_process').fork

// Equivalent to &&
const c1 = fork('./child1.js')
c1.on('exit', (code) => {
  if (code === 0) {
    const c2 = fork('./child2.js', {
      detached: true
    })
  }
})

Enter fullscreen mode Exit fullscreen mode

and

const fork = require('child_process').fork
// Equivalent to ||
const c1 = fork('./child1.js')
c1.on('exit', (code) => {
  if (code !== 0) {
    fork('./child2.js', {
      detached: true
    })
  }
})
Enter fullscreen mode Exit fullscreen mode

Thanks for Reading.

References

https://shapeshed.com/unix-exit-codes/

Top comments (1)

Collapse
 
wangpin34 profile image
Penn • Edited

If the expected bahavior is run the next command no matter the previous ends with error or not, use this:

const fork = require('child_process').fork
// Equivalent to ||
const c1 = fork('./child1.js')
c1.on('exit', () => {
    fork('./child2.js', {
      detached: true
    })
})
Enter fullscreen mode Exit fullscreen mode