binary-diff.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. 'use strict';
  2. const fs = require('fs');
  3. const readChunk = require('read-chunk');
  4. const istextorbinary = require('istextorbinary');
  5. const dateFormat = require('dateformat');
  6. const prettyBytes = require('pretty-bytes');
  7. const Table = require('cli-table');
  8. exports.isBinary = (existingFilePath, newFileContents) => {
  9. const existingHeader = readChunk.sync(existingFilePath, 0, 512);
  10. return istextorbinary.isBinarySync(undefined, existingHeader) ||
  11. (newFileContents && istextorbinary.isBinarySync(undefined, newFileContents));
  12. };
  13. exports.diff = (existingFilePath, newFileContents) => {
  14. const existingStat = fs.statSync(existingFilePath);
  15. const table = new Table({
  16. head: ['', 'Existing', 'Replacement', 'Diff']
  17. });
  18. let sizeDiff;
  19. if (!newFileContents) {
  20. newFileContents = Buffer.from([]);
  21. }
  22. if (existingStat.size > newFileContents.length) {
  23. sizeDiff = '-';
  24. } else {
  25. sizeDiff = '+';
  26. }
  27. sizeDiff += prettyBytes(Math.abs(existingStat.size - newFileContents.length));
  28. table.push([
  29. 'Size',
  30. prettyBytes(existingStat.size),
  31. prettyBytes(newFileContents.length),
  32. sizeDiff
  33. ], [
  34. 'Last modified',
  35. dateFormat(existingStat.mtime),
  36. '',
  37. ''
  38. ]);
  39. return table.toString();
  40. };