index.js 2.1 KB

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