nodeJS - 8 - process process process child_process subprocess

Keywords: node.js Attribute shell Javascript

Process process and child_process subprocesses

Reference resources

1. Process process process

Explain

The process object is a global object of Node, which provides information about the current Node process. It can be used anywhere in the script without requiring the command to load.

Attribute API

  1. The process.argv attribute, which returns an array containing command line parameters when starting the node process
  2. process.env returns an object containing user environment information, which can be added, deleted and modified in scripts.
  3. process.pid returns the process number of the current process
  4. process.platform returns the current operating system
  5. process.version returns the current node version
  6. process.execPath returns the absolute path to the executable file that started the Node.js process
  7. process.execArgv returns command-line parameters between Node executable and script files
  8. Standard input of process.stdin to implement Duplex stream (readable and writable)
  9. process.stdout standard output, to achieve Duplex stream (readable, writable), write() method equivalent to console.log()
  10. process.stderr standard error
    // # node index.js name test
    console.log(process.argv);
    /*    
        [ 
            '/usr/local/bin/node', // process.execPath The absolute path of the executable file that starts the Node process
            '/Users/xxx/node-test/index.js', // Currently executed javascript file path
            'name', // Other command line parameters
            'test' 
        ]
    */

    process.env.test = 'test'; // increase
    console.log(process.env.test); // test query
    process.env.test = 'new'; // change
    console.log(process.env.test); // new
    delete process.env.test; // delete
    console.log(process.env.test); // undefined
    /*
        New environment variable NODE_ENV, marking development stage or production stage
        The command line can use export NODE_ENV = Production & node index.js
    */ 
    process.env.NODE_ENV = 'production'

    console.log(process.pid);  // 3105 

    console.log(process.platform);  // darwin 

    console.log(process.version);  // v8.9.0 

    console.log(process.execPath);  // /usr/local/bin/node

    // # node --harmony index.js
    console.log(process.execArgv);  // [ '--harmony' ]

    let count = 0;
    process.stdin.on('data', function (chunk) {
        process.stdout.write(count++ + ' = ' + chunk);
    })
    process.stdin.on('end', function () {
        process.stdout.write('end');
    })

Method API

  1. process.cwd() returns the current working directory of the node.js process
  2. process.chdir() changes the working directory of the node.js process
  3. process.nextTick(fn) places tasks at the end of the current event cycle and adds them to the'next tick'queue. Once the tasks of the current event polling queue are completed, all callback s in the next tick queue will be invoked in turn.
  4. process.exit() exits the current process, often unnecessary
  5. process.kill(pid[,signal]) sends signals to a specified process, including but not limited to terminating the process
  6. process.emitWarning() issues specific or customized process warnings that can be monitored through process.on('warning)
    console.log(process.cwd()); //  /Users/temp/node-test
    process.chdir('../');
    console.log(process.cwd()); // / Users/temp

    let count = 0;
    process.on('warning', function (warning) {
        console.log(warning);
    })
    process.stdin.on('data', function (chunk) {
        process.nextTick(function () {
            console.log('next tick');
        })
        process.stdout.write(count++ + '=' + chunk); 

        if (count > 3) {
            process.emitWarning('something warning', {
                code: 'WARNING_SOME',
                detail: 'this is warning something'
            })
            process.exit(); // Exit process   
            process.kill(process.pid); // Kill process
        }
        /*
            ss
            undefined undefined
        */
    })

process event

  1. After Node clears EventLoop, the beforeExit event can be triggered without any pending tasks. Some tasks can be deployed here so that the Node process does not quit and the process.exit() displayed will not trigger.
  2. exit event, triggered when the current process exits, only synchronous operation is allowed in the callback function, because after the callback is executed, the process Jinhui exits.
  3. uncaughtException event, triggered when the current process throws an uncovered error, can be used to perform synchronous cleaning of some allocated resources before the end of the process. It is not safe to attempt to use it to restore the normal operation of the application.
  4. Warning event, any process warning issued by Node.js, triggers this event
  5. Signal Events Signal Events, triggered when the Node.js process receives a signal
    let count = 0;
    process.on('beforeExit', function () {
        console.log('beforeExit');
    })
    process.on('exit', function (code) {
        console.log('exit', code);
    })
    process.on('uncaughtException', function (err) {
        console.log('uncaughtException', err);
    })
    process.on('warning', function (warning) {
        console.log('warning', warning);
    })
    process.on('SIGHUP', function () {
        console.log('SIGHUP');
    })

    process.stdout.write('xxx'); 
    process.kill(process.pid, 'SIGHUP')
    /*
        xxx SIGHUP
        beforeExit
        exit 0
    */

2. child_process subprocess

Explain

The child_process module is used to create new sub-processes. The running results of sub-processes are stored in the system cache (up to 200k). When the sub-processes are finished, the main process calls back function to read the running results of sub-processes.

By default, stdin, stdout, stderr pipes will be established between Node.js parent process and derivative process, and data can be circulated in a non-blocking way in the pipeline.

Create subprocesses

1. child_process.spawn() child_process.spwanSync()

The spawn() method provides the same functionality in a synchronous manner, but blocks the event loop and knows that the derived child process exits or terminates.

parameter

  • 1) command: shell script command to execute
  • 2) args: list of string parameters
  • 3) options: configure additional options: cwd: the current working directory of the child process; env: environment variable key-value pairs...
    // test.js content
    process.stdout.write('this is child back');

    // Index.js content executes node index.js
    const child_process = require('child_process');

    const child = child_process.spawn('node', ['test.js'], {
        cwd: './'
    });

    child.stdout.setEncoding('utf-8');
    child.stdout.on('data', function (data) {
        console.log('listen in process', data); // listen in process this is child back 
    })

    const childSync = child_process.spawnSync('node', ['test.js'], {
        cwd: './'
    })

    console.log(childSync); // pid stdout error ...

The following interfaces are all implemented for convenience on top of these two interfaces (spawn(), spawnSync()).

2. child_process.exec() child_process.execSync()

Derives a shell, executes commands in the shell, buffers any generated output, and calls the callback function after running.

  • 1) command: To run commands, space division
  • 2) options: optional, cwd: working directory of subprocesses; env: key pairs of environment variables
  • 3) callback: callback, will pass in three parameters, error: error information; stdout: standard output display results; stdrr: standard error display results
    const child_process = require('child_process');

    child_process.exec('node test.js', function (error, stdout, stderr) {
        if (error) {
            return console.log(error); 
        }

        console.log('stdout', stdout);
        console.log('stderr', stderr);
    })

    const child = child_process.exec('node test.js');

    child.stdout.on('data', function (data) {
        console.log('listen ', data.toString());
    })

    const childSync = child_process.execSync('node test.js');

    console.log(childSync.toString());

3. child_process.execFile() child_process.execFileSync()

Similar to the child_process.exec() function, except that it does not derive a shell, the specified executable file is directly derived into a new process, which is more efficient.

  • 1) file: The name or path of the executable to run
  • 2) args: optional, list of string parameters
  • 3) options: Configuration items are consistent with child_process.exec()
  • 4) callback: callback error; stdout standard output; stderr standard error
    const child_process = require('child_process');

    child_process.execFile('node', ['test.js'], function (error, stdout, stderr) {
        if (error) {
            return console.log(error);
        }

        console.log('stdout', stdout);
        console.log('stderr', stderr);
    })

    const childSync = child_process.execFileSync('node', ['test.js']);

    console.log(childSync.toString());

4. child_process.fork() send()

fork() is used to create a child process directly and return a child process object. Unlike the span method, fork establishes a communication pipeline between parent and child processes for communication between processes.

  • 1) modulePath: Module to run in a subprocess
  • 2) args: list of string parameters
  • 3) option: configuration item cwd: current working directory of subprocesses; env: environment white variable; execpath: execution path used to create subprocesses

send() is used to send messages to new processes, which acquire messages by listening for message events

    const child_process = require('child_process');

    const child = child_process.fork('./test.js');

    // Listen for message events to retrieve the data returned by the child process
    child.on('message', function (m) {
        console.log('process get', m);
    })

    child.send({parentID: process.pid});

Events and attributes of child process objects

Event

  1. close event triggered when the'stdio'stream of the child process is closed
  2. The disconnect event, triggered by subprocess.disconnect() in the parent process or by calling process.disconnect() in the child process, cannot send or receive messages after disconnection.
  3. Error event, triggered when an error occurs
  4. Exit event, triggered after the end of the subprocess, callback parameter code: exit code; signal: signal when terminated
  5. message event, communication between parent and child processes, for receiving information

attribute

  1. connected property, indicating whether messages can still be sent and received from a child process
  2. The disconnect() method closes the IPC channel between the parent process and the child process, and allows the child process to exit normally once there is no other connection to keep it active.
  3. kill([signal]) method, which sends a signal to the child process and terminates the child process by default without writing parameters
  4. killed property, indicating that the child process has been successfully terminated by subprocess.kill()
  5. pid attribute, process identification of subprocesses
  6. Send method, which is used to send information when an IPC channel is established between parent and child processes.
    // Subprocess test.js
    process.on('message', function (m) {
        console.log('child process get ', m);
        if (m === 0) process.send(3);
    })

    // Main process
    const child_process = require('child_process');
    const child = child_process.fork('./test.js');

    child.on('close', function (code, signal) {
        console.log('close code', code);
        console.log('close signal', signal);
    })
    child.on('exit', function (code, signal) {
        console.log('exit code', code);
        console.log('exit signal', signal);
    })
    child.on('disconnect', function () {
        console.log('disconnect', child.connected);
    })
    child.on('error', function (err) {
        console.log('error', err);
    })

    // Listen for message events to retrieve the data returned by the child process
    child.on('message', function (m) {
        console.log('process get', m);
        if (m === 1) child.disconnect();
        if (m === 3) child.kill();
        console.log(child.killed);
    })

    child.send(0);

Posted by LucidParody on Fri, 21 Dec 2018 21:09:05 -0800