replace-sync.js 726 B

123456789101112131415161718192021222324252627282930
  1. 'use strict';
  2. /**
  3. * Dependencies
  4. */
  5. const fs = require('fs');
  6. const makeReplacements = require('./make-replacements');
  7. /**
  8. * Helper to replace in a single file (sync)
  9. */
  10. module.exports = function replaceSync(file, from, to, config) {
  11. //Extract relevant config and read file contents
  12. const {encoding, dry, countMatches} = config;
  13. const contents = fs.readFileSync(file, encoding);
  14. //Replace contents and check if anything changed
  15. const [result, newContents] = makeReplacements(
  16. contents, from, to, file, countMatches
  17. );
  18. //Contents changed and not a dry run? Write to file
  19. if (result.hasChanged && !dry) {
  20. fs.writeFileSync(file, newContents, encoding);
  21. }
  22. //Return result
  23. return result;
  24. };