【问题标题】:NodeJS – Serialport Readline issueNodeJS – Serialport Readline 问题
【发布时间】:2021-09-29 18:11:12
【问题描述】:

在我的第一个问题 (NodeJS and Serialport – Read RFID Card) 之后,我找到了获取正确数据的方法。

但现在我的结果如下:

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());
    });
});
``

【问题讨论】:

    标签: node.js node-serialport


    【解决方案1】:

    我不能 100% 确定您所说的 archive 到底是什么意思,但是,如果您想过滤掉空数据,您可以在 if 语句中使用 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
        }
    });
    

    【讨论】:

    • 感谢您的回复。对不起,我的意思是“实现”。我已经尝试过您的解决方案,但输出中似乎没有任何变化。现在我将每个 Char 作为一行,但我想在一个字符串中获取该数据,所以我可以执行一个 if 语句,如下所示:if(data.length === 10){...}。跨度>
    • 我已使用此信息更新了我的答案。
    • 谢谢,就像一个魅力:-)
    • 没问题!很高兴我能帮上忙。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-08
    相关资源
    最近更新 更多