index.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. 'use strict';
  2. var path = require('path');
  3. var fs = require('fs');
  4. /**
  5. * Check if the file contents at `filepath` conflict with the `contents` passed to the
  6. * function
  7. *
  8. * If `filepath` points to a folder, we'll always return true.
  9. *
  10. * @param {String} filepath Destination filepath (current with to compare with)
  11. * @param {Buffer|String} contents The new content to compare with. If passed as a
  12. * string, we assume it is utf8 encoded.
  13. * @return {Boolean} `true` if there's a conflict, `false` otherwise.
  14. */
  15. module.exports = function (filepath, contents) {
  16. filepath = path.resolve(filepath);
  17. // If file is new, then it's safe to process
  18. if (!fs.existsSync(filepath)) return false;
  19. // If file path point to a directory, then it's not safe to write
  20. if (fs.statSync(filepath).isDirectory()) return true;
  21. var actual = fs.readFileSync(path.resolve(filepath));
  22. if (!(contents instanceof Buffer)) {
  23. contents = new Buffer(contents || '', 'utf8');
  24. }
  25. // We convert each Buffer contents to an hexadecimal string first, and then compare
  26. // them with standard `===`. This trick allow to compare binary files contents.
  27. return actual.toString('hex') !== contents.toString('hex')
  28. };