Skip to content

Instantly share code, notes, and snippets.

@leommoore
Last active May 30, 2023 08:22
Show Gist options
  • Save leommoore/4484379 to your computer and use it in GitHub Desktop.
Save leommoore/4484379 to your computer and use it in GitHub Desktop.
Node - Child Processes

#Node - Processes To launch an external shell command or executable file you can use the child_process. Apart from command line arguments and environment variables you cannot communicate with the process using child_process.exec. However you can use child_process.spawn to create a more integrated processes.

##Executing Child Processes

###To launch an external shell command

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

//exec(command, callback);
exec('ls', function(err,stout,stderr) {
  if (err) {
    console.log('Child process exited with error code', err.code);
    return
  }
  console.log(stdout);
});

###Passing options You can also pass options to the child process.

var child_process = require('child_process');
var exec = child_process.exec;
var options = {
  timeout: 10000,
  killSignal: 'SIGKILL'
}

//exec(command, [options], callback);
exec('ls', options, function(err,stout,stderr) {
  if (err) {
    console.log('Child process exited with error code', err.code);
    return
  }
  console.log(stdout);
});

####Available Process Options

  • cwd - Current working directory. Force process to use current working directory.
  • encoding - Expected encoding for the child output. The default is utf8. Supported encodings are ascii, utf8, ucs2 and base64.
  • timeout - Timeout in milliseconds for the command execution. Default is 0 which wait indefinately
  • killSignal - The signal to be sent to the child process if it times out or exceeds the output buffer. the default is SIGTERM. child_process.spawn allows more fine grained control.
  • env - Environment variables to be passed to the child process. Default is null which means that the child process inherits all the parent environment variables.

####Available Signals

Name Default Action Description
SIGHUP Terminate process Terminal line hangup
SIGINT Terminate process Terminal line hangup
SIGQUIT Create core image Quit program
SIGILL Create core image Illegal instruction
SIGTRAP Create core image Trace trap
SIGABRT Create core image Abort program
SIGFPE Create core image Floating point exception
SIGKILL Terminate process Kill program
SIGBUS Create core image Bus error
SIGSEGV Create core image Segmentation violation
SIGSYS Create core image Nonexistant system call invoked
SIGPIPE Terminate process Software termination signal
SIGALRM Terminate process Real-time timer expired
SIGTERM Terminate process Software termination signal
SIGURG Discard signal Urgent condition present on socket
SIGSTOP Stop process Stop (cannot be caught or ignored)
SIGTSTP Stop process Stop signal generated from keyboard
SIGCONT Discard signal Continue after stop
SIGCHLD Discard signal Child status has changed
SIGTTIN Stop process Backround read attempted from control terminal
SIGTTOU Stop process Backround write attempted from control terminal
SIGIO Discard process I/O is possible on a descriptor
SIGXCPU Terminate process CPU time limit exceeded
SIGXFSZ Terminate process File size limit exceeded
SIGVTALRM Terminate process Virtual time alarm
SIGPROF Terminate process Profiling timer alarm
SIGWINCH Discard process Window size change
SIGINFO Discard process Status request from keyboard
SIGUSR1 Terminate process User defined signal 1
SIGUSR2 Terminate process User defined signal 2

###Passing Environment Variables You can pass new environment variables by copying the existing variables and adjusting as neccessary.

var env = process.env,
    varName,
    envCopy = {};
   
var exec = require('child_process').exec;

// Copy process.env into envCopy
for (varName in env) {
  envCopy[varName] = env[varName];
}

// Assign some custom variables
envCopy['CUSTOM ENV VAR'] = 'some value';
envCopy['CUSTOM ENV VAR 2'] = 'some other value';

// Execute some command with process.env and my custom variables
exec('ls -la', { env: envCopy }, function(err, stdout, stderr) {
  if (err) { throw err; }
  console.log('stdout:', stdout);
  console.log('stderr:', stderr);
});

####Passing Environment Variables - parent.js Here is an example of passing environment variables.

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

exec('node child.js', {env: {number: 123}}, function(err, stdout, stderr) {
  if (err) { throw err; }
  console.log('stdout:\n', stdout);
  console.log('stderr:\n', stderr);
});

####Reading Environment Variables - child.js Here is an example of reading environment variables which have been passed to the child.

var number = process.env.number;
console.log(typeof(number)); // → "string"

number = parseInt(number, 10);
console.log(typeof(number)); // → "number"

##Spawning Child Processes

var spawn = require('child_process').spawn;

var child = spawn()

###Creating a Child Process

@xingchch
Copy link

Can child_process.exec execute 'su' command? I tried but it didn't work.

@karthik93advaitha
Copy link

Hi @xingchch , any luck with this? I'm currently in the same situation where im using "su - B" to change the user from A to B from my node application.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment