node.js - 如何使用 NodeJS 从串行设备流式传输不完整的数据 csv 数据?
问题描述
我有一个简单的 Arduino 草图,看起来像这样(请暂时忽略阻塞延迟)......
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
}
void loop() {
Serial.println("Hello world from Ardunio!\n");
delay(5000);
}
这很好用,所以我创建了一个节点库来与串口通信......
import SerialPort from 'serialport';
import parse from 'csv-parse';
const output=[];
const parser = parse({
to_line: 10
});
const port = new SerialPort('/dev/ttyACM0', {
baudRate: 115200
});
port.on('readable', function () {
let record
while (record = port.read()) {
output.push(record.toString());
console.log(`The collection is \n ${JSON.stringify(output)}`);
}
})
port.on('error', function(err) {
console.log('Error: ', err.message);
});
port.on('close', function(){
console.log('The port is closed');
});
port.on('open', err =>{
console.log("The port is opened");
});
我的期望是这将读取 10 行并停止。但是,当它运行时,我会看到这样的记录...
The collection is
["d from Ardunio!\n\r\n"]
The collection is
["d from Ardunio!\n\r\n","Hello world from Ardu"]
The collection is
["d from Ardunio!\n\r\n","Hello world from Ardu","nio!\n\r\n"]
这当然是不对的,因为缓冲区一次只读取每条记录的片段。处理这些记录并将字符串组合到新行(如果多列则为逗号)的最佳方法是什么(库或滚动我自己的)?
解决方案
推荐阅读
- android - 当另一个应用程序启动/启动时启动/启动 myApp
- javascript - 为什么每次从命令提示符运行 java 脚本文件时都会出现此错误?“参考节点未定义”
- azure - Terraform 有条件地排除资源块
- validation - 我可以在运行时动态设置标签吗?
- python - 可以从 __main__ 以外的 OTHER 启动 Python 多处理进程吗?
- facebook - Facebook Webhook 测试按钮未按预期工作
- postgresql - PostgreSQL 11.5 插入或更新(每个操作都应该添加字段值)
- python - pandas 编译大量数据帧的最快方式
- javascript - JavaScript clearInterval 位置
- sql - 关于最大创建时间和分组依据的 Postgres 查询帮助