feat: a pretty decent, tested, working SDK + CLI
[crowdnode.js/.git] / lib / qr.js
1 "use strict";
2
3 let Qr = module.exports;
4
5 let Fs = require("fs").promises;
6
7 let QrCode = require("qrcode-svg");
8
9 Qr._create = function (data, opts) {
10   return new QrCode({
11     content: data,
12     padding: opts?.padding || 4,
13     width: opts?.width || 256,
14     height: opts?.height || 256,
15     color: opts?.color || "#000000",
16     background: opts?.background || "#ffffff",
17     ecl: opts?.ecl || "M",
18   });
19 };
20
21 Qr.ascii = function (data, opts) {
22   let qrcode = Qr._create(data, opts);
23   let indent = opts?.indent ?? 4;
24   var modules = qrcode.qrcode.modules;
25
26   let ascii = ``.padStart(indent - 1, ' ');
27   let length = modules.length;
28   for (let y = 0; y < length; y += 1) {
29     for (let x = 0; x < length; x += 1) {
30       let block = "  ";
31       if (modules[x][y]) {
32         block = "██";
33       }
34       ascii += block;
35     }
36     ascii += `\n`.padEnd(indent, ' ');
37   }
38   return ascii;
39 };
40
41 Qr.svg = function (data, opts) {
42   let qrcode = Qr._create(data, opts);
43   return qrcode.svg();
44 };
45
46 Qr.save = async function (filepath, data, opts) {
47   let qrcode = Qr.svg(data, opts);
48   await Fs.writeFile(filepath, qrcode, "utf8");
49 };