2017-04-05 6 views
0

이 작동하지 않습니다.Node.js child.stdin.write가 자식 프로세스를 실행하려고 할 때 어떤 텍스트를 stdin 할 때 오류가 발생하면

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(); 

가 발생합니다 :이 프로세스를 실행 스크립트의

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); 
     } 
    } 
} 

코드 :

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) 

통지를, child.stdin와 내가 주석 라인 여기 는 자식 프로세스의 코드 .종료(); 스크립트 작업을해야하는 반응

+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을 사용하십시오.

이에 스크립트를 변경

:

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); 
      } 
     } 

    } 
} 

참조 :

  • NodeJS Spawn Command
  • System.console() returns null
  • ,369

    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); 
    

    그런 다음이에 자바 코드를 변경