Child Process

The child_process module allows you to communicate with other applications on your system by executing external processes in your environment. There are four kinds of child processes; exec(), spawn(), execFile(), fork(). I will be covering exec() and spawn() here. If a child process will execute once, use exec() function. For example the "cal" command on terminal prints the current month's calendar in the terminal. The command is executed once, prints a result and that's it. If a child process would be running for a long time and printing output several times, use spawn() function. An example would be:

tail -f error_log

This command would keep running as long as apache is running and it would continue to print new entries in the error_log as they come.

The following code opens a page in your default browser:

var cp = require("child_process").exec

The following code runs a command in the terminal and displays its output:

var cp = require("child_process").exec;
cp("node -v", function(err, stdout) {
    if (err) {
        throw err;
    console.log("Node version ");

This code runs the command "node -v" on the command line. This command returns the version of node installed on your system. This stdout output is then displayed by this program.