本文介绍了使用终端将信息输入 Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取一个 c++ 程序的输出并将其输入到一个 javascript 文件的 stdin 中.但是我一直无法使用该方法将任何内容推送到标准输入中...

I want to take the output of a c++ program and input it into the stdin of a javascript file. However I have been unable to push anything into the stdin using the method...

node example.js < test.txt

因为我收到以下错误.

example.js:35

stdin.setRawMode(true);

stdin.setRawMode( true );

TypeError: undefined 不是函数

TypeError: undefined is not a function

在对象.(example.js:35:7)

at Object. (example.js:35:7)

在 Module._compile (module.js:460:26)

at Module._compile (module.js:460:26)

在 Object.Module._extensions..js (module.js:478:10)

at Object.Module._extensions..js (module.js:478:10)

在 Module.load (module.js:355:32)

at Module.load (module.js:355:32)

在 Function.Module._load (module.js:310:12)

at Function.Module._load (module.js:310:12)

在 Function.Module.runMain (module.js:501:10)

at Function.Module.runMain (module.js:501:10)

启动时 (node.js:129:16)

at startup (node.js:129:16)

在 node.js:814:3

at node.js:814:3

违规代码如下所示.它在正常输入期间工作正常,但在上述情况下崩溃.

The offending code appears to be as below. It works fine during normal input, however crashes in the above scenario.

var stdin = process.stdin;
stdin.setRawMode( true );
stdin.resume();
stdin.setEncoding( 'utf8' );
stdin.on( 'data', function( key ){
//do stuff based upon input

有没有人遇到过这个问题,或者任何关于如何解决它的想法?或者解决这个问题的另一种方式?

Has anyone encountered this, or any ideas about how to fix it? Or another way of going about this problem?

推荐答案

使用重定向的标准输入运行程序时,您连接的是 ReadStream,而不是 TTY,因此不支持 TTY.setRawMode().

When running your program with redirected stdin, you're connected to a ReadStream, not a TTY, so TTY.setRawMode() isn't supported.

setRawMode() 用于设置 tty 流,使其不以任何方式处理其数据,例如提供对换行的特殊处理.这种处理过的数据被称为熟化".

setRawMode() is used to set a tty stream so that it does not process its data in any way, such as providing special handling of line-feeds. Such processed data is referred to as being "cooked".

根据定义,标准节点 ReadStreams 已经是原始的",因为没有对数据进行特殊处理.

Standard node ReadStreams are, by definition, already "raw" in that there is no special processing of the data.

因此,在不调用 setRawMode() 的情况下重构您的代码,它应该可以正常工作.

So, refactor your code without the call to setRawMode() and it should work fine.

这篇关于使用终端将信息输入 Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 16:52