Getting full credit card data using javascript

618 Views Asked by At

I have been trying to get the credit card data from Desko Keyboard which I eventually succeeded but the problem is I'm getting card data in a different pattern every time I swipe

Below is my JS code

var fs = require('Serialport');
function listenDevice() {
  this.port = fs('COM8');
  let dataComplete = '';
  let count = 0;
  this.port.on('open', () => {
    console.log('sp: ' + this.port.path + ' port open event');
    this.port.set({ dtr: true, rts: true }, function (err) {
      if (err) {
        console.log('Set Error: ', err.message);
        this.isServiceError = true;
        this.serviceErrorText = err;
      }
    });
  });

  this.port.on('data', (data) => {
    console.log('sp: Data: ', data.toString('utf-8'));
  });
}

This is the Pattern of the card data I'm getting:

sp: Data: CBZZZZZZZZZZZZZZZZ^XXXXXXXX sp: Data: XXXX X ^18082261485500005000000 !ZZZZZZZZZZZZZZZZ sp: Data: =1808226000005

sp: Data: CBZZZZZZZZZZZZZZZZ^XXXXXXXX sp: Data: XXXX X ^18082261485 sp: Data: 500005000000 !ZZZZZZZZZZZZZZZZ=1808226000005

sp: Data: CBZZZZZZZZZZZZZZZZ^XXXXXXXX sp: Data: XXXX X ^18082261485500005000000 !ZZZZZZZZZZZZZZZZ=1808226000005

Here X denotes the Card Holder Name Z denotes the Card Number

As you can sp: Data:log has been called twice or thrice but the card data is similar. I want to concat this card data no matter how the data is coming. Any idea.

And I'm using serial port to read the data

1

There are 1 best solutions below

0
Brad On

You can't assume you'll have all the data in a single data event. You need to buffer data, and using the information you know about the protocol, determine when you have enough.

Since you're only expecting a small amount of data, it's acceptable to have a running buffer of data concatenated together.

You'll want to do something like this:

let buffer;
this.port.on('data', (data) => {
  buffer = Buffer.concat([buffer, data]);
  if (/* your code to determine if you have enough data */) {
    const packet = buffer.slice(0, /* expected length */);
    buffer = buffer.slice(/* expected length*/);
    console.log(packet.toString());
  }
});