Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Child Process(exec or spawn) In Node JS

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.88k
    Comment on it

    As we all know that Node.js runs in a single thread mode and in order to achieve performance it make use of event-driven methodology. This event-driven methodology make Node.js efficient for I/O processes , but sometime there are cases where applications require more CPU and which might block event-loop which is considered as heart of Node.js . In order to take care of this situation where application can slow down due to I/O intensive operation node try to externalize these kind of operations so that we can keep our event-loop free.

     

    In order to achieve parallel processing Node.Js make use of child processes. Node have an inbuilt module(Child_process) which can be required and used as per your requirement.

     

    Module 'child_process' has two major inbuilt functions known as 'spawn' and 'exec' which can be used in order to start child processes as needed.

     

    1) The exec() method

    exec() command runs the command directly in the shell and returns the whole buffer output from the child process at last once the command finishes its execution. exec() method has the following signature in node.js :

     

    child_process.exec(command[, options], callback)

     -> command String The command to run, with space-separated arguments

     -> options Object may comprise one or more of the following options:

            -> cwd String Current working directory of the child process

            -> env Object Environment key-value pairs

            -> encoding String (Default: 'utf8')

            -> shell 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 Number (Default: 0)

            -> maxBuffer Number (Default: 200*1024)

            -> killSignal String (Default: 'SIGTERM')

            -> uid Number Sets the user identity of the process.

            -> gid Number Sets the group identity of the process.

    -> callback Function gets three arguments error, stdout and stderr which is called with the following output when process terminates

     

    An example of code making use of exec() :

     

    var download_file = function(file_url) {
        var file_name = url.parse(file_url).pathname.split('/').pop();
        var wget = 'wget -P ' + DOWNLOAD_DIR + ' ' + file_url;
        // excute wget using child_process' exec function
        var child = exec(wget, function(err, stdout, stderr) {
            if (err) throw err;
            else console.log(file_name + ' downloaded to ' + DOWNLOAD_DIR);
        });
    };

     

    We are making use of exec() in the above example because we only need to download some file on our machine and return status on basis of it. We are hardly interested in buffer and streams. If the case would have been opposite we would need spawn() for the same code-base other then exec()

     

    2) The spawn() method

     

    spawn() kicks off a new process after the required command is given. It also ensures return of an object with stdout and stderr streams. If you intend to read data that the child process sends back to Node, you need to tap on the stdout stream.Since stdout is a stream, it encompasses "data", "end", and other events that streams have. The best use of spawn is made when you wish the return of a large amount of data, like image processing, reading binary data etc, to Node via the child process. spawn() has the following signature :

     

    child_process.spawn(command[, args][, options])

     -> command String The command to run

     -> args Array List of string arguments

     -> options Object may comprise one or more of the following options:

            -> cwd String Current working directory of the child process

            -> env Object Environment key-value pairs

            -> stdio Array|String Child's stdio configuration

            -> customFds Array Deprecated File descriptors for the child to use for stdio

            -> detached Boolean The child will be a process group leader

            -> uid Number Sets the user identity of the process.

            -> gid Number Sets the group identity of the process.

     

    An example of code making use of spawn() :

    var download_file = function(file_url) {
        // extract the file name
        var file_name = url.parse(file_url).pathname.split('/').pop();
    
        // create an instance of writable stream
        var file = fs.createWriteStream(DOWNLOAD_DIR + file_name);
    
        // execute curl using child_process' spawn function
        var curl = spawn('curl', [file_url]);
    
        // add a 'data' event listener for the spawn instance
        curl.stdout.on('data', function(data) { file.write(data); });
    
        // add an 'end' event listener to close the writeable stream
        curl.stdout.on('end', function(data) {
            file.end();
            console.log(file_name + ' downloaded to ' + DOWNLOAD_DIR);
        });
    
        // when the spawn child process exits, check if there were any errors and close the writeable stream
        curl.on('exit', function(code) {
            if (code != 0) {
                console.log('Failed: ' + code);
            }
        });
    };

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: