utf8.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. var Utils = require('./utils')
  2. var BLOCK_CHAR = {
  3. WW: ' ',
  4. WB: '▄',
  5. BB: '█',
  6. BW: '▀'
  7. }
  8. var INVERTED_BLOCK_CHAR = {
  9. BB: ' ',
  10. BW: '▄',
  11. WW: '█',
  12. WB: '▀'
  13. }
  14. function getBlockChar (top, bottom, blocks) {
  15. if (top && bottom) return blocks.BB
  16. if (top && !bottom) return blocks.BW
  17. if (!top && bottom) return blocks.WB
  18. return blocks.WW
  19. }
  20. exports.render = function (qrData, options, cb) {
  21. var opts = Utils.getOptions(options)
  22. var blocks = BLOCK_CHAR
  23. if (opts.color.dark.hex === '#ffffff' || opts.color.light.hex === '#000000') {
  24. blocks = INVERTED_BLOCK_CHAR
  25. }
  26. var size = qrData.modules.size
  27. var data = qrData.modules.data
  28. var output = ''
  29. var hMargin = Array(size + (opts.margin * 2) + 1).join(blocks.WW)
  30. hMargin = Array((opts.margin / 2) + 1).join(hMargin + '\n')
  31. var vMargin = Array(opts.margin + 1).join(blocks.WW)
  32. output += hMargin
  33. for (var i = 0; i < size; i += 2) {
  34. output += vMargin
  35. for (var j = 0; j < size; j++) {
  36. var topModule = data[i * size + j]
  37. var bottomModule = data[(i + 1) * size + j]
  38. output += getBlockChar(topModule, bottomModule, blocks)
  39. }
  40. output += vMargin + '\n'
  41. }
  42. output += hMargin.slice(0, -1)
  43. if (typeof cb === 'function') {
  44. cb(null, output)
  45. }
  46. return output
  47. }
  48. exports.renderToFile = function renderToFile (path, qrData, options, cb) {
  49. if (typeof cb === 'undefined') {
  50. cb = options
  51. options = undefined
  52. }
  53. var fs = require('fs')
  54. var utf8 = exports.render(qrData, options)
  55. fs.writeFile(path, utf8, cb)
  56. }