finalize.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Finalize Nodejs Script
  2. // 1 - Append JS in HTML Document
  3. // 2 - Gzip HTML
  4. // 3 - Covert to Raw Bytes
  5. // 4 - ( Save to File: webpage.h ) in dist Folder
  6. const fs = require('fs');
  7. const zlib = require('zlib');
  8. const { gzip } = require('@gfx/zopfli');
  9. function getByteArray(file){
  10. let fileData = file.toString('hex');
  11. let result = [];
  12. for (let i = 0; i < fileData.length; i+=2)
  13. result.push('0x'+fileData[i]+''+fileData[i+1]);
  14. return result;
  15. }
  16. let js = fs.readFileSync(__dirname+'/dist/js/app.js');
  17. let html = `
  18. <!DOCTYPE html>
  19. <html lang="en">
  20. <head>
  21. <meta charset="utf-8">
  22. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  23. <meta name="viewport" content="width=device-width,initial-scale=1.0">
  24. <title>WebSerial</title>
  25. <script data-name="BMC-Widget" async src="https://cdnjs.buymeacoffee.com/1.0.0/widget.prod.min.js" data-id="6QGVpSj" data-description="Support me on Buy me a coffee!" data-message="You can always support my work by buying me a coffee!" data-color="#FF813F" data-position="right" data-x_margin="24" data-y_margin="24"></script>
  26. </head>
  27. <body>
  28. <noscript>
  29. <strong>We're sorry but WebSerial doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
  30. </noscript>
  31. <div id="app"></div>
  32. <script>${js}</script>
  33. </body>
  34. </html>
  35. `;
  36. // Gzip the index.html file with JS Code.
  37. const gzippedIndex = zlib.gzipSync(html, {'level': zlib.constants.Z_BEST_COMPRESSION});
  38. let indexHTML = getByteArray(gzippedIndex);
  39. let source =
  40. `
  41. const uint32_t WEBSERIAL_HTML_SIZE = ${indexHTML.length};
  42. const uint8_t WEBSERIAL_HTML[] PROGMEM = { ${indexHTML} };
  43. `;
  44. fs.writeFileSync(__dirname+'/dist/webpage.h', source, 'utf8');
  45. // Produce a second variant with zopfli
  46. // Zopfli is a improved zip algorithm by google
  47. // Takes much more time and maybe is not available on every machine
  48. const input = html;
  49. gzip(input, {numiterations: 15}, (err, output) => {
  50. indexHTML = output;
  51. let source =
  52. `
  53. const uint32_t WEBSERIAL_HTML_SIZE = ${indexHTML.length};
  54. const uint8_t WEBSERIAL_HTML[] PROGMEM = { ${indexHTML} };
  55. `;
  56. fs.writeFileSync(__dirname + '/dist/webpage_zopfli.h', source, 'utf8');
  57. });