index.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. var es = require('event-stream');
  2. var rs = require('replacestream');
  3. var stream = require('stream');
  4. var istextorbinary = require('istextorbinary');
  5. module.exports = function(search, replacement, options) {
  6. var doReplace = function(file, callback) {
  7. var isRegExp = search instanceof RegExp;
  8. var isStream = file.contents && typeof file.contents.on === 'function' && typeof file.contents.pipe === 'function';
  9. var isBuffer = file.contents instanceof Buffer;
  10. function doReplace() {
  11. if (isStream) {
  12. file.contents = file.contents.pipe(rs(search, replacement));
  13. return callback(null, file);
  14. }
  15. if (isBuffer) {
  16. if (isRegExp) {
  17. file.contents = new Buffer(String(file.contents).replace(search, replacement));
  18. }
  19. else {
  20. var chunks = String(file.contents).split(search);
  21. var result;
  22. if (typeof replacement === 'function') {
  23. // Start with the first chunk already in the result
  24. // Replacements will be added thereafter
  25. // This is done to avoid checking the value of i in the loop
  26. result = [ chunks[0] ];
  27. // The replacement function should be called once for each match
  28. for (var i = 1; i < chunks.length; i++) {
  29. // Add the replacement value
  30. result.push(replacement(search));
  31. // Add the next chunk
  32. result.push(chunks[i]);
  33. }
  34. result = result.join('');
  35. }
  36. else {
  37. result = chunks.join(replacement);
  38. }
  39. file.contents = new Buffer(result);
  40. }
  41. return callback(null, file);
  42. }
  43. callback(null, file);
  44. }
  45. if (options && options.skipBinary) {
  46. istextorbinary.isText('', file.contents, function(err, result) {
  47. if (err) {
  48. return callback(err, file);
  49. }
  50. if (!result) {
  51. return callback(null, file);
  52. } else {
  53. doReplace();
  54. }
  55. });
  56. }
  57. else {
  58. doReplace();
  59. }
  60. };
  61. return es.map(doReplace);
  62. };