My basic requirement is to look for changes done to any file in js
,css
folder and update a JSON file.
Directory structure:
- html
- css
- x.css
- y.css
- js
- a.js
- b.js
- c.js
- server
- versions.json
- css
versions.json
:
{
"css": {
"x.css": 1,
"y.css": 1,
},
"js": {
"a.js": 1,
"b.js": 1,
"c.js": 1,
},
}
As I make any changes to any of the files in js
and css
folder, I want gulp to return the name of the file that was saved and look for the key in versions.json
and increase its value by 1
i.e. if I save a.js
then it should update only the value of "a.js"
in versions.json
to 2
.
Here's what I've done:
gulp.task('upgrade-file-version', function() {
gulp.src('server/versions.json')
.pipe(modify({
fileModifier: function(file, contents)
{
var fileContent = contents;
var parsedObj = JSON.parse(fileContent);
var dir = 'js'; // folder name
var filename = 'a.js'; // file name
var oldVersion = parsedObj[dir][filename];
var newVersion = oldVersion + 1;
parsedObj[dir][filename] = newVersion;
var newFileContent = JSON.stringify(parsedObj, null, 4);
return newFileContent;
}
}))
.pipe(gulp.dest('server/'));
});
Plugin: gulp-modify
The variables dir
and filename
needs to have the value of the folder and name of the changed file.
Any improvement over this or even an another approach is fine