Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does require("child_process") actually do?

When we call :

var p = require(child_process);

Are we already creating a child process ? (if not, what is the p here?)

To explain my confusion futher, in a codebase i picked up, i see :

var childProcess1 = require("child_process");
var  _retrieveChild = childProcess1.fork(
           __dirname + '/backgroundProcesses/DadProcess',
           { execArgv: ['--debug=5859'] }
        );

I am asking myself whether it is creating yet another process from a child process or is the childProcess1 just a badly chosed name?

like image 909
Orkun Ozen Avatar asked Dec 29 '14 13:12

Orkun Ozen


2 Answers

Requiring modules can sometimes initialize the module, so don't feel bad about not knowing. They are all different. However, child_process does not create a process simply by requiring the module as you have done. You have to call either fork() or spawn() (or exec()) to actually create a new process (and PID).

If you look at the documentation you can see how sometimes they will use this syntax:

var spawn = require('child_process').spawn;
// ...
spawn('ps', ['ax']);

which basically grabs the module API, then the spawn method off of that and aliases it to a local variable for use later in the code.

EDIT

Just to expand on this for your understanding generally, inside of a Node module, the module decides what to "export". Whatever it exports is what will be returned from the require(...) call. For example, if we had this module:

// foo.js
module.exports = function() {
    return "bar";
};

Then require("foo") would give us a function (but it would not have been called yet):

var mymodule = require("foo");
var result = mymodule(); // <-- this calls the function returned via module.exports
console.log(result); // "bar"
like image 77
Jordan Kasper Avatar answered Sep 19 '22 13:09

Jordan Kasper


The child_process module acts as a namespace for the spawn, exec, execFile, and fork functions. You call require("child_process") to refer to the module, and then call one of its member functions to create a new process.

The return value of each of those functions is a ChildProcess object, which represents the spawned process and has members like stdin, stdout, and pid.

like image 24
apsillers Avatar answered Sep 21 '22 13:09

apsillers