• node child_process


    1.所有的开启的子进程都是 require(child_process).spawn的基础上实现的

      child_process 产生的进程,都是独立于主进程的,有自己的内存和v8实例

    2.在 Node.js 的父进程与衍生的子进程之间会建立 stdinstdout 和 stderr 的管道。 数据能以非阻塞的方式在管道中流通

    包括四个方法:

    child_process.spawn()child_process.fork()child_process.exec() 和 child_process.execFile()

    3.child_process.exec() 中callback的构成是

      function(err, stdout, stderr)  {} 注意第一个是err参数。

    4.child_process.fork(modulePath[, args][, options])

      1.衍生一个新的node.js进程

      2.返回的 ChildProcess 会有一个额外的内置的通信通道,它允许消息在父进程和子进程之间来回传递

      3.每个进程都有自己的内存(独立于主进程的内存),使用自己的 V8 实例

    5.主要区别:

      child_process.fork('./worker.js')  

      child_process.exec('node ./worker.js', function(err, stdout,stderr) {})

      child_process.execFile('./worker.js', function(err, stdout, stderr) {})

      child_process.spawn('node',['worker.js'])

    区别:

      1.exec和execFile都带有callback,而fork和spawn没有callback

      2.exec, execFile , fork可以创建任意的进程(exec可以执行一条命令exec('cat *.js bad_file | wc -l', (error, stdout, stderr) => {}),

        spawn只能创建 node进程

    启动子进程的用法,一般在正常启动的文件中加入启动子进程的另一个文件。

    父进程的代码:

    const cp = require('child_process');
    const n = cp.fork(`${__dirname}/sub.js`);
    
    n.on('message', (m) => {
      console.log('父进程收到消息:', m);
    });
    
    // Causes the child to print: CHILD got message: { hello: 'world' }
    n.send({ hello: 'world' });  //父进程向子进程发送的消息


    子进程的代码:
    process.on('message', (m) => {
      console.log('子进程收到消息:', m);
    });
    
    // Causes the parent to print: PARENT got message: { foo: 'bar', baz: null }
    process.send({ foo: 'bar', baz: NaN });  //子进程向父进程发送消息

    Node.js 中的子进程有一个自己的 process.send() 方法,允许子进程发送消息回父进程。
    与cluster向对比,cluster中有一个worker.send()方法,允许子进程向主进程发送消息。
    只能在父进程中调用的方法和监听的事件:
      1.child_process.on('close', cb) //只能父进程使用
      2.child_process.on('exit', cb)
    //只能父进程使用
      3.child_process.on('error', cb)//只能父进程使用
      4.child_porcess.on('disconnect', cb)//只能父进程使用
      5.child_process.send()    //向子进程发送消息
      6.
    child_process.kill()   //只能在父进程中调用
      7.child_process.disconnect() //只能在父进程中调用
      7.child_process.pid     //父进程中和子进程都可以获取到这个
    在子进程调用的方法和事件以及属性:
      1.process.
    connected //是否连接,true未连接 false未连接
      2.process.pid //获取pid
      3.process.send()
      4.process.on('message', cb)

      

  • 相关阅读:
    vuecli3title标签中的htmlWebpackPlugin.options.title
    vuecli3根据不同环境配置axios的baseUrl
    处理uniapp(同理小程序)开发中使用richtext富文本解析,图片未自适应宽度问题(图片显示不全)
    echart相关
    uniapp richtext图片自适应处理
    app云端打包失败 云端服务器返回错误
    [Violation] Added nonpassive event listener to a scrollblocking 'mousewheel' event.
    elinput textarea autosize 的坑
    iOS手机上input输入框无法输入bug
    ttf转eot
  • 原文地址:https://www.cnblogs.com/jay--zhang/p/8124386.html
Copyright © 2020-2023  润新知