replace-async.js 998 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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 (async)
  9. */
  10. module.exports = function replaceAsync(file, from, to, config) {
  11. //Extract relevant config
  12. const {encoding, dry, countMatches} = config;
  13. //Wrap in promise
  14. return new Promise((resolve, reject) => {
  15. fs.readFile(file, encoding, (error, contents) => {
  16. //istanbul ignore if
  17. if (error) {
  18. return reject(error);
  19. }
  20. //Make replacements
  21. const [result, newContents] = makeReplacements(
  22. contents, from, to, file, countMatches
  23. );
  24. //Not changed or dry run?
  25. if (!result.hasChanged || dry) {
  26. return resolve(result);
  27. }
  28. //Write to file
  29. fs.writeFile(file, newContents, encoding, error => {
  30. //istanbul ignore if
  31. if (error) {
  32. return reject(error);
  33. }
  34. resolve(result);
  35. });
  36. });
  37. });
  38. };