0

I am a bit new to child-process and require an additional clarification about it.

My case

I'm looking for way to run/trigger one js file as a separate/isolated process from another js file. Without using direct require or import as, but pass a certain argument (number in my case) from parent to child process.

parent.js

async function parent () {

    /** logic */

    /** run/start child.js script with certain (1) argument from logic above /

    /** if logic below fails, it won't crash/trigger child, and his job will be finished separately outside async function*/
}

child.js

async function child(number) {
    /** receive argument from parent.js and execute separately*/
}

Just to be sure, schema:

    MAIN THREAD 
        |
        |
      run child => CHILD THREAD (receive number arg from main thread)
        |               |
        x               | (don't care about error in main thread)
     (error)            |
  END OF M_THREAD       |
                        |
                        V
                    (ok, filled)

So I have read could of articles about child_process and official node.js docs, and know that there are:

  • fork
  • exec
  • child

modes. And I could also run a separate npm task from my parent.js file (via pm2 for example), but I have no idea what should I use and what suits my needs in this case. So any advice, explanation will be helpful and will be rewarded by up-voting from me.

AlexZeDim
  • 3,520
  • 2
  • 28
  • 64
  • 1
    If it needs to be a separate process and you want to directly control it from a parent process or communicate with it via node's simple communication mechanisms, then that's what child_process is for. If you don't need to control it from the parent, but you just want it started at the same time, you can use some outside agent such as a shell script or pm2 to start both your processes at once. – jfriend00 May 16 '20 at 21:11
  • I don't need to control child process. I just want to pass argument from parent to it. As for now I am looking for `spawn` and it seems `fine` for that case, but I don't know for sure. `PM2` is also an option, but I want to use `in-house` node.js magic, without any other extensions – AlexZeDim May 16 '20 at 21:13
  • 1
    Then, just use `spawn()` and move on. There's no big thing to optimize for here. If `spawn()` works, use it. It seems like you're overthinking this. – jfriend00 May 16 '20 at 21:41

1 Answers1

1

You can check here, providing simple example how to do that. https://zaiste.net/nodejs-child-process-spawn-exec-fork-async-await/ Hope it will help you.

ant_dev
  • 653
  • 8
  • 16