Child Process EXEC
Node.js child_process.exec() method
This method will runs a command in console and buffers the output. And we have tried provide some example to cover this point.
Syntax:-
child_process.exec(command[, options], callback)
Parameters:-
(1)command:-First parameter in above method is command. And this specifies the command to run, with space-separated arguments.
(2)options:-When we say about the options this may contain one or more of the below options:-
- cwd:-Here we will specifies the current working directory of the child process.
- env:-Here we will specifies the environment key-vakue pairs.
- encoding:-Here we will specifies encoding algo like we mention String (Default: 'utf8')
- shell:-It specifies string Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should understand the -c switch on UNIX or /s /c on Windows. On Windows, command line parsing should be compatible with cmd.exe.)
- timeout:-Here we will specifies the Number (Default: 0)
- maxBuffer:-Here we will specifies the Number (Default: 200*1024)
- killSignal:-Here we will specifies the String (Default: 'SIGTERM')
- uid Number:-Here we will sets the user identity of the process.
- gid Number:-Here we will sets the group identity of the process.
(3)callback:-Here on callabck parameter,this callabck function specifies three argument error, stdout and stderr which is called with the following output when process terminates.
Node.js child_process.exec() example 1
Now jump to first example of child_process. Here we have take the simple process example to print architecture, pid, platform and version of the process.
File: child_processexample1.js
Now we will create a batch file named my.bat having the following code:
File: my.bat
dirmkdir child
Now we will open the Node.js command prompt and run the below code:-
node child_processexample1.js
Once we execute the js file there are two commands executed that are dir and mkdir child. Here dir command will display the list of the current directory and nkdir command will create a new directory. And when we say about the linux you need to run the ls command to display the current directory list.
Below is calling and execution of js file in node.js.
And above command will create a new folder.
Node.js child_process.exec() example 2
Now here in 2nd example we will create two js file and first file is support.js and second file in master.js. With below code:-
File: support.js
console.log("Child Process " + process.argv[2] + " executed." );
File: master.js
Now open Node.js command and then on command prompt run the below command:-
node master.js
| |