91-9990449935 0120-4256464 |
Node.js Child ProcessThe Node.js child process module provides the ability to spawn child processes in a similar manner to popen(3). There are three major way to create child process:
Node.js child_process.exec() methodThe child_process.exec() method runs a command in a console and buffers the output. Syntax: Parameters: 1) command: It specifies the command to run, with space-separated arguments. 2) options: It may contain one or more of the following options:
callback: The callback function specifies three arguments error, stdout and stderr which is called with the following output when process terminates. Node.js child_process.exec() example 1Let's see the simple process example to print architecture, pid, platform and version of the process. File: child_process_example1.js Create a batch file named my.bat having the following code: File: my.bat Open Node.js command prompt and run the following code: It will execute two commands dir and mkdir child. The dir command will display list of current directory and mkdir command will create a new directory. For linux, you can you ls command to display the current directory list. It will create a new directory also. Node.js child_process.exec() example 2Create two js files named support.js and master.js, having the following code: File: support.js File: master.js Open Node.js command prompt and run the following code: Node.js child_process.spawn() methodThe child_process.spawn() method launches a new process with a given command. This method returns streams (stdout & stderr) and it is generally used when the process returns large amount of data. Syntax: Parameters: 1) command: It specifies the command to run. 2) args: It specifies an array List of string arguments. 3) options: It may contain one or more of the following options:
Node.js child_process.spawn() exampleCreate two js files named support.js and master.js, having the following code: File: support.js File: master.js Open Node.js command prompt and run the following code: Node.js child_process.fork() methodThe child_process.fork method is a special case of the spawn() to create Node processes. This method returns object with a built-in communication channel in addition to having all the methods in a normal ChildProcess instance. Syntax: Parameters: 1) modulePath: This is a string specifies the module to run in the child. 2) args: It specifies an array List of string arguments. 3) options: It may contain one or more of the following options:
Node.js child_process.fork() exampleCreate two js files named support.js and master.js, having the following code: File: support.js Open Node.js command prompt and run the following code:
Next TopicNode.js Buffer
|