我正在尝试基于节点的内部process.stdio创建一个节点模块,以使用stdin
,stdout
,stderr
的对象与任何进程无关方式,传递和模仿。
由于某些原因,它很难测试这个文件。即使是new Stdio()
的最小测试似乎也“阻止”或“挂起”开玩笑。 --forceExit
有效,但还有一些奇怪或奇怪的行为。以下代码是否有任何特定内容会导致进程挂起?
这是:
const tty = require('tty')
export function getStdout () {
var stdout
const fd = 1
stdout = new tty.WriteStream(fd)
stdout._type = 'tty'
stdout.fd = fd
stdout._isStdio = true
stdout.destroySoon = stdout.destroy
stdout._destroy = function (er, cb) {
// Avoid errors if we already emitted
er = er || new Error('ERR_STDOUT_CLOSE')
cb(er)
}
// process.on('SIGWINCH', () => stdout._refreshSize())
return stdout
}
export function getStderr () {
var stderr
const fd = 2
stderr = new tty.WriteStream(fd)
stderr._type = 'tty'
stderr.fd = fd
stderr._isStdio = true
stderr.destroySoon = stderr.destroy
stderr._destroy = function (er, cb) {
// Avoid errors if we already emitted
er = er || new Error('ERR_STDOUT_CLOSE')
cb(er)
}
// process.on('SIGWINCH', () => stderr._refreshSize())
return stderr
}
export function getStdin () {
var stdin
const fd = 0
stdin = new tty.ReadStream(fd, {
highWaterMark: 0,
readable: true,
writable: false
})
stdin.fd = fd
stdin.on('pause', () => {
if (!stdin._handle) { return }
stdin._readableState.reading = false
stdin._handle.reading = false
stdin._handle.readStop()
})
return stdin
}
export function setupStdio () {
var stdio = {}
Object.defineProperty(stdio, 'stdout', {
configurable: true,
enumerable: true,
get: getStdout
})
Object.defineProperty(stdio, 'stderr', {
configurable: true,
enumerable: true,
get: getStderr
})
Object.defineProperty(stdio, 'stdin', {
configurable: true,
enumerable: true,
get: getStdin
})
return stdio
}
export default class Stdio {
constructor () {
const {stdin, stderr, stdout} = setupStdio()
this.stdin = stdin
this.stderr = stderr
this.stdout = stdout
return this
}
}
这在Jest中挂起了这个过程,为什么?
import Stdio from './index'
test('works', () => {
const x = new Stdio()
expect(x).toBeTruthy()
})