【问题标题】:How to use CLI application from node.js child process?如何从 node.js 子进程使用 CLI 应用程序?
【发布时间】:2017-09-01 08:57:23
【问题描述】:

我正在措辞如何使用来自 node.js 的命令行界面的应用程序。这是 node.js 代码:

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

child.stdout.pipe(process.stdout);
child.stdin.write("tratata\r\n;");

child.stdin.end();

它运行 java HelloWorld cli 应用程序。

这里是java代码:

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

但它不起作用。当child.stdin.write 执行时 - 什么也没发生。

【问题讨论】:

    标签: node.js command-line-interface node.js-stream


    【解决方案1】:

    免责声明:我对 Java 几乎一无所知。

    我的猜测是java.io.Console 不仅仅是从标准输入读取数据,比如打开控制台设备(在大多数类 Unix 操作系统上为/dev/tty)本身,从而绕过传入的stdin/stdout/stderr 设备按节点。

    如果你使用java.io.BufferedReader,效果会更好:

    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    
    public class HelloWorld {
        public static void main(String[] args) {
            System.out.println("started");
    
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    
            while (true) {
                try {
                    String s = reader.readLine();
                    if (s == null) return; // end of stream reached
                    System.out.println("Your sentence:" + s);
                } catch(IOException e) {
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-09-29
      • 2011-06-11
      • 1970-01-01
      • 1970-01-01
      • 2016-07-25
      • 2017-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多