Last active
August 28, 2017 08:20
-
-
Save uchcode/a09f77e9f5411d6cb425afd792d9065d to your computer and use it in GitHub Desktop.
electron ruby example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="text/javascript"> | |
function electron_spawn(cmd,arg) { | |
let p = require('child_process').spawn(cmd,arg) | |
p.stdout.ondata=(action,listener)=>{ | |
p.stdout.on('data',(data)=>{ | |
let d = JSON.parse(data.toString()) | |
if (d.action == action) listener(d) | |
}) | |
} | |
p.on('exit',(code,signal)=>{ | |
console.log(`child process exited:${code} signal:${signal}`) | |
}) | |
p.on('disconnect',()=>{ | |
console.log('child process disconnect.') | |
window.alert('child process disconnect.') | |
}) | |
p.on('error',(err)=>{ | |
console.error('child process error:',err) | |
window.alert('child process error:'+err.toString()) | |
}) | |
p.stderr.on('data',(data)=>{ | |
console.error('stderr:',data.toString()) | |
window.alert('stderr:'+data.toString()) | |
}) | |
window.addEventListener('beforeunload',(event)=>{ | |
p.kill() | |
}) | |
return p | |
} | |
</script> | |
<title>communication process demo</title> | |
<body> | |
<h1>Addition</h1> | |
<form id="frm" method="post" onsubmit="return false;"> | |
<input type="number" step="0.1" name="x" placeholder="x" required> + | |
<input type="number" step="0.1" name="y" placeholder="y" required> = | |
<input type="number" step="0.1" id="z" placeholder="z"> | |
<input type="submit" id="btn"> | |
</form> | |
</body> | |
<script id="ruby" type="text/plain"> | |
STDOUT.sync = true | |
require 'json' | |
loop do | |
Thread.start JSON.parse(gets.chomp) do |input| | |
case input['action'] | |
when 'addition' | |
output = { | |
:action => :addition, | |
:z => input['x'] + input['y'] | |
} | |
puts output.to_json | |
else | |
STDERR.puts 'input:', input | |
end | |
end | |
end | |
</script> | |
<script type="text/javascript"> | |
scpt = document.getElementById('ruby').innerText | |
proc = electron_spawn('ruby',['-e',scpt]) | |
proc.stdout.ondata('addition',(data)=>{ | |
document.getElementById('z').value = data.z | |
document.getElementById('btn').disabled = false | |
}) | |
document.getElementById('frm').addEventListener('submit',(evt)=>{ | |
document.getElementById('btn').disabled = true | |
let data = new FormData(evt.target) | |
let json = { | |
action: 'addition', | |
x: parseFloat(data.get('x')), | |
y: parseFloat(data.get('y')), | |
} | |
proc.stdin.write(JSON.stringify(json)+'\n') | |
}) | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment