26
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Node.js から Ruby を外部コマンド実行し、標準出力を随時受け取る

Last updated at Posted at 2016-01-31

2016/2/2 追記 : コメントを参考に追記いたしました。

概要

こんにちは。アレクスです。
今回はですね。 Node.jsからrbファイルを実行して、
標準出力を受け取ることについて解説します。

長いこと中途半端に取り組み見て見ぬふりしていました問題が、
以外にもサクッ:cookie:と解決してしまいなんだか :frowning: だったのですが、
落とし穴なポイントが有りましたので、公開いたします。

今回は超初期段階です、これから複雑な実装を行いますので、
また投稿したいと思います。

最終目的

Rubyで作ったプログラムをElectronから実行して、標準出力を受け取って、
画面に表示させたいですね。プログレスバーに反映できれば great!ですね。

イメージ
Rubyで進行状況のパーセンテージ計算 => 数値をstdout
Node.jsで受け取り => GUIのプログレスバーデザイン部分のwidthに随時反映

初期段階

まずは Node.js から外部コマンドで、簡単な Ruby コードを実行してみます。
エラーもどうなるか合わせてみてみます。

hello.rb

# coding: utf-8
Encoding.default_external = 'UTF-8'

begin

  5.times {
    print "HELLO WORLD!"
    sleep(0.5)
  }

  raise "ERROR"

rescue => ex
  print ex.class
  print ex.message
  print ex.backtrace
end

Node.js は以下のようにspawnを使います。

open3.js
const spawn = require('child_process').spawn;
const ls = spawn('ruby', ['hello.rb']);

ls.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

ls.stderr.on('data', (data) => {
  console.log(`stderr: ${data}`);
});

ls.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

参考:Child Process Node.js v5.5.0 Manual & Documentation

でもはじめは実行してもうまく行かなかったんですよね :crying_cat_face:

原因

原因は2つありました。

  • Ruby側のstdoutpでないとダメ
    putsでもprintでも実験したらダメでした。
  • ちゃんとターミナルでしてなかったのでダメ
    Sublime Text3のビルドツールでやってました。

p以外でやった場合は、随時ではなく全て終わってから帰ってきますね。
SublimeText3のビルドツールでrunすると以下のエラーが出ました。


events.js:154
      throw er; // Unhandled 'error' event
      ^

Error: spawn ruby ENOENT
    at exports._errnoException (util.js:856:11)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:178:32)
    at onErrorNT (internal/child_process.js:344:16)
    at nextTickCallbackWith2Args (node.js:474:9)
    at process._tickCallback (node.js:388:17)
    at Function.Module.runMain (module.js:449:11)
    at startup (node.js:139:18)
    at node.js:999:3

以上、簡単ではございましたがご紹介でした。

最後に

間違いやもっと良い方法があるよ! :smiley:
という時などぜひにコメントお願い致します。

Original Post

追記

ruby側の出力バッファリングをやめることにより、putsprintでも、随時出力が可能となりました。
pine613様ありがとうございました。

hello.rb

# coding: utf-8
Encoding.default_external = 'UTF-8'
##
# 追記部分
STDOUT.sync = true

begin

  5.times {
    print "HELLO WORLD!"
    sleep(0.5)
  }

  raise "ERROR"

rescue => ex
  print ex.class
  print ex.message
  print ex.backtrace
end

26
29
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?