• nodejs 服务终端使用 nodemon 运行脚本时实时输出


    nodejs 服务终端使用 nodemon 运行脚本时实时输出

    • 运行命令 node run.js
    • run.js 中又运行了命令 node server.js
    • 要求 server.js 中由 cp.spawn 运行的命令能在控制台实时输出

    使用 nodemon 来运行 server.js

    • run.js
    /**
    # nodejs 服务终端实时输出
    - 运行命令 node run.js
    - run.js 中又运行了命令 node server.js
    - 要求 server.js 中由 cp.spawn 运行的命令能在控制台实时输出
     */
    
    new Promise(async () => { // 启动 server.js
      const nodemon = require(`nodemon`)
      nodemon({
        ignoreRoot: [],
        exec: `node "server.js"`,
        watch: [`server.js`],
        stdout: false,
      })
      .on('readable', function(arg) { // the `readable` event indicates that data is ready to pick up
        // console.log(`readable`, arg)
        this.stdout.pipe(process.stdout) // 把子进程的输出定向到本进入输出
        this.stderr.pipe(process.stderr) // 错误输出, 例如按需安装依赖时无权限
        this.stdout.on(`data`, data => {
          log = String(data)
        })
      })
    })
    
    

    动态安装依赖

    • server.js
    new Promise(async () => {
      const cmd = `cnpm i cnpm@6.1.1 --product --no-save --registry=https://registry.npm.taobao.org/`
      // const cmd = `tree`
      console.log(`cmd`, cmd)
      await spawn(
        `npx`, cmd.split(/s+/),
        {
          // stdio: [0, `pipe`, 2], // 仅 server.js 可实时输出
          // stdio: `pipe`, // x
          // stdio: `ignore`, // x
          // stdio: `inherit`, // x
          // stdio: [process.stdin, process.stdout, process.stderr], // x
          // stdio:  [ 'ignore', 1, 2 ], // x
          // detached: true,
          // stdio: "inherit"
        }
      )
      console.log(`运行结束`)
    })
    
    /**
     * 以 Promise 方式运行 spawn
     * @param {*} cmd 主程序
     * @param {*} args 程序参数数组
     * @param {*} opts spawn 选项
     */
    function spawn (cmd, args, opts) {
      opts = { stdio: `inherit`, ...opts }
      opts.shell = opts.shell || process.platform === 'win32'
      return new Promise((resolve, reject) => {
        const cp = require('child_process')
        const child = cp.spawn(cmd, args, opts)
        let stdout = ''
        let stderr = ''
        child.stdout && child.stdout.on('data', d => { stdout += d; console.log(`stdout`, stdout) })
        child.stderr && child.stderr.on('data', d => { stderr += d; console.log(`stderr`, stderr) })
        child.on('error', reject)
        child.on('close', code => {
          resolve({code, stdout, stderr})
        })
      })
    }
    

    以上代码摘自 mockm

  • 相关阅读:
    Datesheet 参数手册
    2017.10.23 Arduino Atmel EFM32低功耗监测
    New Concept English three(21)
    The disadvantage for manager has a part-time job as a trainer
    New Concept English three(20)
    Python+Qt学习随笔:PyQt中常用的事件处理函数
    Python+Qt学习随笔:PyQt图形界面应用的事件处理流程
    PyQt学习遇到的问题:重写notify发送的消息为什么首先给了一个QWindow对象?
    PyQt学习随笔:PyQt中捕获键盘事件后获取具体按键值的方法
    PyQt学习随笔:重写组件的event方法捕获组件的事件
  • 原文地址:https://www.cnblogs.com/daysme/p/14623018.html
Copyright © 2020-2023  润新知