Wednesday, 17 October 2018

Node.js: child_process.exec(command[, options][, callback]) : Execute system commands

child_process module allows user to execute external processes. For example, you can comunicate external applications (like notepad++) installed in your system.

HelloWorld.js
var exec = require('child_process').exec;

var applicationName = 'notepad';
exec(applicationName);


When you execute above application in windows environment, it opens notepad application.

Signature of exec function looks like below.
child_process.exec(command[, options][, callback])
Below table summarizes the arguments of exec function.

Argument
Type
Description
command
String
Command to execute
Options
Object
Below table summarizes different options provided by exec command.

Option
Type
Description
cwd
string
Current working directory of child process. Default value is null.
env
Object
Environment key, value pairs. Default value is null.
encoding
string
Default valueis utf-8. If encoding is 'buffer', or an unrecognized character encoding, Buffer objects will be passed to the callback instead.
shell
string
Shell to execute the command with. Default: '/bin/sh' on UNIX, process.env.ComSpec on Windows.
timeout
number
Default value is 0. If timeout is greater than 0, the parent will send the signal identified by the killSignal property (the default is 'SIGTERM') if the child runs longer than timeout milliseconds.
maxBuffer
number
Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated.
Kill
string or integer
Default: 'SIGTERM'
Uid
number
Sets the user identity of the process
Gid
number
Sets the group identity of the process
windowsHide
boolean
Hide the subprocess console window that would normally be created on Windows systems. Default: false.
callback
Function
Function to be called, when the process terminates. This function takes three arguments.

Below table summarizes the arguments of callback function.

Argument
Type
error
Error
stdout
String (or) Buffer
stderr
String (or) Buffer

On success, error will be null. On error, error will be an instance of Error.

stdout and stderr objects represents the stdout and stderr output of the child process.


Previous                                                 Next                                                 Home

No comments:

Post a Comment