index.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * barcode generator
  3. */
  4. var fs = require('fs'),
  5. path = require('path');
  6. module.exports = function (moduleName, options) {
  7. options.data = options.data || '';
  8. options.barcolor = options.barcolor || '#000';
  9. options.bgcolor = options.bgcolor || '#FFF';
  10. options.w = options.width || 0;
  11. options.h = options.height || 0;
  12. options.type = (options.type) ? options.type.toUpperCase().trim() : 'PNG';
  13. return new Barcode(moduleName, options);
  14. }
  15. function Barcode(moduleName, options) {
  16. this.barcode = require('./lib/' + moduleName.toLowerCase());
  17. this.options = options;
  18. }
  19. Barcode.prototype.getStream = function (callback) {
  20. this.barcode.createCode(this.options, function (err, stream) {
  21. callback(err, stream);
  22. });
  23. }
  24. Barcode.prototype.saveImage = function (outfile, callback) {
  25. this.getStream(function (err, stream) {
  26. if (err) return callback(err, '');
  27. var ws = fs.createWriteStream(outfile);
  28. stream.pipe(ws);
  29. stream.on('end', function () {
  30. callback(false, outfile);
  31. });
  32. stream.on('error', function (err) {
  33. callback(err, '');
  34. });
  35. });
  36. }
  37. Barcode.prototype.getBase64 = function (callback) {
  38. var type = this.options.type || 'PNG';
  39. this.getStream(function (err, stream) {
  40. if (err) return callback(err, '');
  41. var imgBufs = [];
  42. stream.on('data', function (chunk) {
  43. imgBufs.push(chunk);
  44. });
  45. stream.on('end', function () {
  46. var src = 'data:image/' + type + ';base64,';
  47. src += Buffer.concat(imgBufs).toString('base64');
  48. callback(false, src);
  49. });
  50. stream.on('error', function (err) {
  51. callback(err, '')
  52. });
  53. });
  54. }