NodeJS – Serialport Readline 问题

NodeJS – Serialport Readline issue

在我的第一个问题 () 之后,我找到了获取正确数据的方法。

但现在我的结果如下:

data received:
data received: 0
data received: >
data received: 0
data received: 0
data received: 6
data received: 3
data received: 4
data received: :
data received: ;
data received: 4
data received:

我想要的输出如下

0>00634:;4

如何使用此代码实现此目的:

var SerialPort = require('serialport');
const Readline = require('@serialport/parser-readline');

var sp = new SerialPort('/dev/tty.usbserial-0001', {
    parser: new Readline(' '),
    baudRate: 4800,
    parity: 'none',
    newline: ' ',
});

sp.on('open', function () {
    console.log('open');
    sp.on('data', function (data) {
        console.log('data received: ' + data.toString());
    });
});
``

我不是 100% 确定 archive 到底是什么意思,但是,如果您想过滤掉空数据,您可以在 [=15] 中使用 data.toString() 输出=]声明。

示例:

sp.on('data', function (data) => {
    const stringData = data.toString();

    if (stringData) {
        console.log(`data received: ${stringData}`);
    }
});

如果您想将此数据写入文件,只需添加:

fs.appendFileSync('output.bin', stringData);

在数据回调中,您可以自行决定是否要附加空白数据,方法是将其放入或放在 if 语句之外。

编辑

根据一些更新的信息,答案如下。为了分隔信息,数据事件应该是这样的:

// Putting the package in a higher scope to make sure that the contents stay after the data event
let package = "";

sp.on('data', function (data) => {
    const stringData = data.toString();

    if (stringData) {
        package += stringData;
    } else {
        // All the string processing goes here, use package for the result

        package = ""; // Resetting the package to collect the next package
    }
});