How to get mongo shell output(three dot) for unterminated command

隐身守侯 提交于 2019-12-25 09:27:56

问题


When type a unterminated command in a mongo shell, it will return three dots indicating need more input to complete this command like below:

> db.test.find(
... {
... 

I am using nodejs child_process.spawn to create a mongo shell process and listen on its output. I can get the standard and error output from the mongo shell but I can't get the ... output. Below is my nodejs code:

const shell = spawn('mongo', params);
      shell
        .stdout
        .on('data', (data) => {
          winston.debug('get output ' + data);

        });

      shell
        .stderr
        .on('data', (data) => {
          const output = data + '';
          winston.error('get error output ', data);

        });

I run below code to send command on the shell:

shell.stdin.write('db.test.find(');

I wander why I can't get the ... output on above method. Is it a special output?

EDIT1

I tried to use node-pty and pty.js. They can get the ... output but they mix the input and output data together. It is not possible to separate them. I also tried to use stdbuf and unbuffer to disable buffer but it still doesn't work. It seems that nodejs child_process doesn't work well with interactive command.


回答1:


Your code doesn't include anything that writes to the stdin of your child process so I would be surprised if you got the ellipsis that indicates incomplete command when in fact you don't send any command at all - incomplete or otherwise.

That having been said, many command line utilities behave differently when they discover a real terminal connected to their stdin/stdout. E.g. git log will page the results when you run it directly but not when you pipe the results to some other command like git log | cat so this may also be the case here.

This can also have to do with the buffering - if your stream is line-buffered then you won't see any line that is not ended with a newline right away.

The real question is: do you see the > prompt? Do you send any command to the mongo shell?

Scritping interactive CLI tools can be tricky. E.g. see what I had to do to test a very simple interactive program here:

  • https://github.com/rsp/rsp-pjc-c01/blob/master/test-z05.sh#L8-L16

I had to create two named pipes, make sure that stdin, stderr and stdout are not buffered, and then use some other tricks to make it work. It is a shell script but it's just to show you an example.



来源:https://stackoverflow.com/questions/42130677/how-to-get-mongo-shell-outputthree-dot-for-unterminated-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!