2017-04-05 4 views
0

が動作しません。何らかのテキストをstdinするとエラーになります。ここ は、子プロセスのコードです:このプロセスを実行するスクリプトのNode.js child.stdin.writeは子プロセスを実行しようとすると

import java.io.Console; 

public class HelloWorld { 
    public static void main(String[] args) { 
     System.out.println("started"); 

     Console console = System.console(); 

     while (true) { 
      String s = console.readLine(); 
      System.out.println("Your sentence:" + s); 
     } 
    } 
} 

コード:

var spawn = require('child_process').spawn; 

var child = spawn('java', ['HelloWorld', 'HelloWorld.class']); 


child.stdin.setEncoding('utf-8'); 

child.stdout.pipe(process.stdout); 


child.stdin.write("tratata\n"); 

// child.stdin.end(); 

それがスローされます:私はchild.stdinと行のコメントを解除

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

Error: read ECONNRESET 
    at exports._errnoException (util.js:1028:11) 
    at Pipe.onread (net.js:572:26) 

通知を、 。終わり();スクリプトを動作させるために必要な任意の反応

+0

FWIW 'child.stdin.setEncoding( 'utf-8');'が正しくありません。 'setEncoding()'は 'Readable'ストリーム用ですが、' child.stdin'は 'Writable'ストリームとして使われます。 – mscdex

+0

また、行末にLFの代わりにCRLFを使用してみましたか(たとえば、 'child.stdin.write(" tratata \ r \ n ");')? – mscdex

答えて

0

一つのことを追加することでしたwhithoutそれだけで終了します。あなたがchild.stdin.write前にこれを追加した場合

process.stdin.pipe(child.stdin); 

が、それは問題の半分を解決するだろう。残りの半分はJava側と関係がありました。 java HelloWorldと入力してJavaプログラムをコンソールから起動しないと、Consoleはnullを返します。Console.readLineを使用しようとすると、NullPointerExceptionが返されます。これを修正するには、代わりにBufferedReaderを使用します。

これにスクリプトを変更し

const spawn = require('child_process').spawn; 
const child = spawn('java', ['HelloWorld'], { 
    stdio: ['pipe', process.stdout, process.stderr] 
}); 

process.stdin.pipe(child.stdin); 
setTimeout(() => { 
    child.stdin.write('tratata\n'); 
}, 1000); 

次にこれにJavaコードを変更します。

import java.io.BufferedReader; 
import java.io.InputStreamReader; 

import java.io.IOException; 

public class HelloWorld { 
    public static void main(String[] args) throws IOException { 
     System.out.println("started"); 

     try(BufferedReader console = new BufferedReader(new InputStreamReader(System.in))) { 
      for (String line = console.readLine(); line != null; line = console.readLine()) { 
       System.out.printf("Your sentence: %s\n", line); 
      } 
     } 

    } 
} 

参照:

関連する問題