【发布时间】:2018-11-03 01:30:19
【问题描述】:
我有一个 nodejs 程序的小问题。我正在尝试使用 child_process 模块,但以下代码只会在我从 nfc 读卡器中取出卡后触发 data 事件。
问题是我需要的输出在卡被移除之前就已经可用了。
例如,如果我将卡放在读卡器上,则需要半秒钟才能打印出一些包含卡 UID 的行。
如果我不释放卡,程序nfc-poll 仍然可以工作,但不会输出任何内容。一旦我从读卡器中取出我的卡,它就会输出一些东西,然后关闭缓冲区。这是发出事件data 的时间。
我想要的是能够尽快读取每个字节以尽快发出卡 ID。
function NFCReader() {
this.reader = new events.EventEmitter()
this.start_process()
}
NFCReader.prototype = {
start_process: function () {
this._process = cp.spawn('nfc-poll', [], {})
this._process.on('close', this.restart_process.bind(this))
//this._process.stdout.on('data', this.handle_data.bind(this))
this._process.stdout.readableFlowing = true
this._process.stdout.on('data', this.handle_data.bind(this))
this._process.stderr.on('data', this.handle_error.bind(this))
},
handle_data: function (data) {
var _data = data.toString()
var uid_lines = _data
.split('\n')
.filter(function (line) {return line.search('UID') >= 0})
if (uid_lines.length != 1) {
this.reader.emit('error', 'Multiple UID found')
return
}
var card_id = uid_lines[0]
.trim()
.split(':')[1].trim()
.replace(/[ ]+/g, ':')
this.reader.emit('card', card_id)
},
}
我尝试使用管道,但似乎没有帮助。
【问题讨论】:
标签: node.js stream child-process