Skip to content

Instantly share code, notes, and snippets.

@Shwartz
Created January 10, 2017 15:01
Show Gist options
  • Save Shwartz/0b380fea8f6491d527a9ef4f55bead8a to your computer and use it in GitHub Desktop.
Save Shwartz/0b380fea8f6491d527a9ef4f55bead8a to your computer and use it in GitHub Desktop.
Using Gulp and Node to change file content based on a string pattern
gulp.task('update-content-file', function () {
"use strict";
var fs = fs || require('fs');
var path = 'path/to/folder';
// example of CSS path change and adding new css
var oldContent = /<link href="(.*)dev\/css\/main.css" rel="stylesheet">/;
var newContent = '<link href="/dev/css/main.css" rel="stylesheet"><link href="/dev/css/specific.css" rel="stylesheet">';
fs.readdir(path, function(err, files) {
files.forEach(function (file) {
// testing if has 'html' string in file name, not testing images, xml etc
if(/html/.test(file) ) {
// remove files based on some name
if (/someString/.test(file)) {
// remove all backup files
fs.unlink(path + '/' + file, (err) => {
if (err) throw err;
});
} else {
// Read file
fs.readFile(path + '/' + file, 'utf8', function (err, data) {
if (err) {
return console.log(err);
}
// looking for string pattern and replacing old -> new
var result = data.replace(CSSOldPath, CSSNewPath);
// writing back
fs.writeFile(path + '/' + file, result, 'utf8', function (err) {
if (err) return console.log(err);
});
// Writing in terminal changed files
console.log('File name: ', file);
})
}
}
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment