为什么Node.js正在等待从child_process.spawn发布标准输出流数据?
我刚开始在为什么Node.js正在等待从child_process.spawn发布标准输出流数据?,node.js,electron,spawn,Node.js,Electron,Spawn,我刚开始在Electron中构建应用程序,因此如果我在这个问题中使用了不恰当的词语结构,我提前表示歉意 在学习过程中,我只是尝试将从我过去创建的IRC bot收集的所有STDOUT数据发送到应用程序中的div元素 index.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Bot World!</title> </
Electron
中构建应用程序,因此如果我在这个问题中使用了不恰当的词语结构,我提前表示歉意
在学习过程中,我只是尝试将从我过去创建的IRC bot收集的所有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>
package.json
只是调用main.js
文件
IRC Bot的源代码:
似乎无论我连接到哪个网络,Electron
应用程序都会等待一定数量的字节,然后再发布到控制台.log
并附加到输出中
我了解到Node的exec
命令将使其将数据读入缓冲区
,而spawn
应允许您实时点击该数据
当程序本身将数据推送到STDOUT
时,如何将其实时发布到应用程序
作为记录,我还尝试使用了
execFile
,但它没有像我预期的那样实现我的愿望。我设法找到了自己答案的解决方案
显然,默认情况下,Ruby
、Python
,以及其他应用程序/语言都会将数据发送到缓冲区中的STDOUT
特别是为了解决运行的Ruby
脚本的问题,我必须使用以下行启用STDOUT同步
:
$stdout.sync=true
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()
}
})