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?
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"
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With