javascriptarraysreplacegulpgulp-replace

How to replace array values with values in another array using gulpjs


I have an XML file where I need to replace attribute values with the values from an array using GulpJS. The existing attribute values in array users1 needs to be replaced with the items in users2 array.

JavaScript code:

var gulp = require('gulp');
var replace = require('gulp-replace');
var rs = require('replacestream');
var through = require('through2');

gulp.task('default', function() {
    //array is dynamic
    var users1 = ["existing_value1", "existing_value2", "existing_value3"];
    var users2 = ["new_value1", "new_value2", "new_value3"];
    var num = users.length();

        gulp.src(['idmap/*.xml'])
            .pipe(replaceArray(users1, users2))
            .pipe(gulp.dest('build/'));
});


function replaceArray(searchArray, replacement) {
    return through.obj(function(file, encoding, callback) {
        if (file.isBuffer()) {
            var result = searchArray.reduce(function(contents, searchArray) {
                return contents.split(searchArray).join(replacement);
            }, String(file.contents));
            file.contents = new Buffer(result);
            return callback(null, file);
        }
        callback(null, file);
    });
}

Sample XML:

<?xml version="1.0"?><IDMAP>
<RECORD>
    <TOKEN data="414" />
    <NAME data="existing_value1" />
</RECORD>
<RECORD>
    <TOKEN data="420" />
    <NAME data="existing_value2" />
</RECORD>
<RECORD>
    <TOKEN data="361" />
    <NAME data="existing_value3" />
</RECORD></IDMAP>

With the above code, I'm getting all values (users1 array) in the XML being replaced by the comma separated values in users2 array. How to replace all the items with the corresponding ones in array?

Thanks in advance!


Solution

  • Your replaceArray() function is not necessary. You already require() the gulp-replace plugin, so I suggest you use it. The solution becomes trivial when using gulp-replace:

    var gulp = require('gulp');
    var replace = require('gulp-replace');
    
    gulp.task('default', function() {
      var users1 = ["existing_value1", "existing_value2", "existing_value3"];
      var users2 = ["new_value1", "new_value2", "new_value3"];
    
      var stream = gulp.src(['idmap/*.xml']);
      users1.forEach(function(u, i) {
        stream = stream.pipe(replace(users1[i], users2[i]));
      });
      return stream.pipe(gulp.dest('build/'));
    });