forked from alba-ado/nfc-pcsc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
from-readme-3.js
63 lines (44 loc) · 1.58 KB
/
from-readme-3.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
"use strict";
// #############
// Example from "Reading and writing data" section of project's README
// #############
import { NFC } from '../src/index';
const nfc = new NFC();
nfc.on('reader', reader => {
console.log(`${reader.reader.name} device attached`);
reader.on('card', async card => {
console.log();
console.log(`card detected`, card);
// example reading 12 bytes assuming containing text in utf8
try {
// reader.read(blockNumber, length, blockSize = 4, packetSize = 16)
const data = await reader.read(4, 12); // starts reading in block 4, continues to 5 and 6 in order to read 12 bytes
console.log(`data read`, data);
const payload = data.toString(); // utf8 is default encoding
console.log(`data converted`, payload);
} catch (err) {
console.error(`error when reading data`, err);
}
// example write 12 bytes containing text in utf8
try {
const data = Buffer.allocUnsafe(12);
data.fill(0);
const text = (new Date()).toTimeString();
data.write(text); // if text is longer than 12 bytes, it will be cut off
// reader.write(blockNumber, data, blockSize = 4)
await reader.write(4, data); // starts writing in block 4, continues to 5 and 6 in order to write 12 bytes
console.log(`data written`);
} catch (err) {
console.error(`error when writing data`, err);
}
});
reader.on('error', err => {
console.log(`${reader.reader.name} an error occurred`, err);
});
reader.on('end', () => {
console.log(`${reader.reader.name} device removed`);
});
});
nfc.on('error', err => {
console.log('an error occurred', err);
});