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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM