0

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

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

Devang Mistry
  • 402
  • 2
  • 5
  • 21
  • Why do you want to use Gulp for that? Just rewrite the file with `fs` methods. You can use Gulp to watch for file changes, though. – MaxArt Jan 08 '17 at 09:05
  • @MaxArt What's `fs` methods ? – Devang Mistry Jan 08 '17 at 09:06
  • I mean [these methods](https://nodejs.org/api/fs.html). In particular `readFile` and `writeFile`. – MaxArt Jan 08 '17 at 09:10
  • I have no idea of node.js. Can you show how I can use it in the above code? – Devang Mistry Jan 08 '17 at 09:19
  • How are you even executing Gulp task if you're not using Node.js? Fact is, you are: Node is the underlying environment, with all its built-in APIs. All you need to do is something like `var fs = require('fs');` and then you're ready, use `fs.readFile` and so on. I suggest reading Node's documentation before proceeding, you'll have a much clearer idea. – MaxArt Jan 08 '17 at 09:34

0 Answers0