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

原文地址:https://www.cnblogs.com/daysme/p/14623018.html