node.js - 为什么 Node.js 等待从 child_process.spawn 发布 STDOUT 流数据?

标签 node.js electron spawn

我刚刚开始考虑在 Electron 中构建应用程序,因此,如果我在这个问题中以不合适的方式使用单词结构,我提前表示歉意。

在学习过程中,我只是尝试将从我过去创建的 IRC 机器人收集的所有 STDOUT 数据发送到应用程序中的 div 元素。

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Bot World!</title>
  </head>
  <body>
    <h1>Bot World!</h1>
    <button type="button" id="bot_button">Run Bot</button>
    <p id="output"></p>
  </body>

<script>
  document.getElementById('bot_button').addEventListener("click", function (e) {

    var spawn = require('child_process').spawn;
    var child = spawn('ruby' , ['/home/syncthetic/Projects/Box/bots/hackthissite']);

    child.stdout.on('data', function(data) {
      console.log('stdout: ' + String(data));
      document.getElementById('bot_button').innerHTML += String(data) + '</b>';
    });

    child.stderr.on('data', function(data) {
      console.log('stdout: ' + String(data));
      document.getElementById('bot_button').innerHTML += String(data) + '</b>';
    });

    child.on('exit', function(code) {
      console.log('stdout: ' + String(data));
      document.getElementById('bot_button').innerHTML += String(data) + '</b>';
    });

 })
 </script>
 </html>

main.js

const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow

let mainWindow

function createWindow () {
  mainWindow = new BrowserWindow({width: 800, height: 600})
  mainWindow.loadURL(`file://${__dirname}/index.html`)
  mainWindow.webContents.openDevTools()

  mainWindow.on('closed', function () {
    mainWindow = null
  })

}


app.on('ready', createWindow)

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', function () {
  if (mainWindow === null) {
    createWindow()
  }
})

package.json 只是调用 main.js 文件

IRC 机器人来源:https://github.com/syncthetic/Box/

看来,无论我连接到哪个网络,Electron 应用程序都会等待特定数量的字节,然后再发布到 console.log 并附加到输出 div

我读到,Node 的 exec 命令会导致它将数据读入缓冲区,而 spawn 应该允许您点击实时输入该数据。

当程序本身将数据推送到 STDOUT 时,如何才能将其实时发布到应用程序?

郑重声明,我还尝试使用 execFile,但它未能达到我的预期,如我所愿。

最佳答案

我设法找到了自己答案的解决方案!

显然Ruby , Python ,毫无疑问其他应用程序/语言会将数据发送到 STDOUT默认情况下在缓冲区中。

专门修复运行 Ruby 的问题脚本,我必须启用 STDOUT syncing与以下行:

$stdout.sync = true

关于node.js - 为什么 Node.js 等待从 child_process.spawn 发布 STDOUT 流数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40252616/

相关文章:

javascript - 根据可选路线的不同查询 -expressjs

javascript - 如何在 Electron 中为两个窗口制作 redux 商店

javascript - Electron 选择带有文本输入和 onclick 事件的目录

spawn - 在 IDL 中使用 spawn 命令

node.js - 使用 Open Shift PaaS 部署 nodejs 应用程序

javascript - Node.JS onoff 未正确拾取 GPIO

javascript - Firebase 不适用于 NodeJS

angular - Electron Angular 库错误

node.js - FFMPEG 和 Node.js Spawn 不输出任何内容

linux - 在 Linux 中使用 Expect Spawn 命令的 SCP