Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/422.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Node.js process.stdin与typescript(tty.ReadStream与ReadableStream)的问题_Javascript_Node.js_Typescript - Fatal编程技术网

Javascript Node.js process.stdin与typescript(tty.ReadStream与ReadableStream)的问题

Javascript Node.js process.stdin与typescript(tty.ReadStream与ReadableStream)的问题,javascript,node.js,typescript,Javascript,Node.js,Typescript,我在Node.js中使用了一些javascript代码来捕获用户输入: if (process.stdin.isTTY) { process.stdin.setRawMode(true) process.stdin.setEncoding('utf8') process.stdin.resume() // safe shutdown if key 'q' is pressed process.stdin.on('data', key => { if (

我在Node.js中使用了一些javascript代码来捕获用户输入:

if (process.stdin.isTTY) {
  process.stdin.setRawMode(true)
  process.stdin.setEncoding('utf8')
  process.stdin.resume()    

  // safe shutdown if key 'q' is pressed
  process.stdin.on('data', key => {
    if (key === 'q') {
      console.log('quit')
      ...
      process.exit()
    }
  })
}
...
这个很好用。现在,我尝试在TypeScript中执行同样的操作,但是在这里,当我尝试传输代码时,我得到了错误:

错误TS2339:类型“ReadableStream”上不存在属性“setRawMode”

因此,我对代码做了一点修改,我用stdin属性的正确类型将所有内容封装在一个类中:

import * as tty from 'tty'

class MyClass {
  private stdin: tty.ReadStream

  constructor() {
    this.stdin = process.stdin
  }

  exec() {
    if (this.stdin.isTTY) {
      this.stdin.setRawMode(true)
      this.stdin.setEncoding('utf8')
      this.stdin.resume()    

      // safe shutdown if key 'q' is pressed
      this.stdin.on('data', (key:string) => {
        if (key === 'q') {
          console.log('quit')
          ...
          process.exit()
        }
      })
    }
    ...
  }
}

const myClass = new MyClass()

myClass.exec()
由于我的类属性stdin的类型为tty.ReadStream,以前未知的方法setRawMode是已知的,但现在,构造函数中的赋值失败,原因是:

错误TS2322:类型“ReadableStream”不可分配给类型“ReadStream”。 类型“ReadableStream”中缺少属性“isRaw”

那么,我做错了什么?我怎样才能解决这个问题?同样,在JavaScript中,一切都很好


我在使用Node.js 7.5.0、TypeScript 2.1.5、ARMv7上的@types/Node 7.0.5(Raspberry Pi2)

遇到了同样的问题;升级到最新的节点v6.10。 它的API文档有点毛茸茸的,但我成功地为构建和运行修改了代码:

const tty = require('tty')
if (tty.isatty(0))
    tty.ReadStream().setRawMode(true)

参见一个工作示例:
npm安装xvt

一个简单的解决方案是将
any
类型分配给
stdin

const stdin:any=process.stdin

试图设置正确的类型或将类型断言应用于
进程.stdin
会导致进一步的类型脚本错误(就像您在问题中描述的那样)

在我看来,Typescript无法处理
进程。stdin
是两种不同的类型,无论是net.Socket还是Readable,请参见:

process.stdin属性返回连接到stdin(fd 0)的流。它是一个net.Socket(双工流),除非fd0引用一个文件,在这种情况下它是一个可读流


如果知道正确的解决方案是什么,那就太好了。

我不知道这是否有点晚,但这也编译了:

import * as tty from "tty";
if(process.stdin instanceof tty.ReadStream){
  process.stdin.setRawMode(true);
}