Reputation: 1295
I am trying to update a json value from a grunt task i have.
This bit of code works
var number = 123456;
var setRandomNumber = function() {
var fs = require('fs');
var fs = require('fs-extra');
var filename = 'my.json';
var config = JSON.parse(fs.readFileSync(filename), 'utf8');
console.log(config.randomNumber);
};
setRandomNumber();
What I want to do is update config.randomNumber to be the value of number.
Can anyone point me in the right direction?
Ta
Upvotes: 0
Views: 664
Reputation: 10906
here is an example of updating the version of the package.json file using a grunt task. (from 0.0.0 to 1.0.0 to 2.0.0);
module.exports = function(grunt) {
grunt.registerTask('version', function(key, value) {
var projectFile = "package.json";
if (!grunt.file.exists(projectFile)) {
grunt.log.error("file " + projectFile + " not found");
return true; //return false to abort the execution
}
var project = grunt.file.readJSON(projectFile), //get file as json object
currentVersion = project["version"].split('.');
currentVersion[lastIndex] = Number(currentVersion[0]) + 1
currentVersion = currentVersion.join('.');
project["version"] = currentVersion;
grunt.file.write(projectFile, JSON.stringify(project, null, 2));
});
}
now you can call the task version to increment the file by writing
grunt version
or you can add it to your production process, for example:
module.exports = function(grunt) {
grunt.registerTask('buildProd', [
'version'
]);
};
Upvotes: 1