Updating file references in a json file via a grunt task

前端 未结 3 579
无人共我
无人共我 2021-02-04 07:15

I\'m a JavaScript developer and fairly new to creating a build process from scratch. I chose to use Grunt for my current project and have created a GruntFile that does about 90%

相关标签:
3条回答
  • 2021-02-04 07:20

    I do something similar - you can load your manifest, update the contents then serialize it out again. Something like:

    grunt.registerTask('fixmanifest', function() {
         var tmpPkg = require('./path/to/manifest/manifest.json');
    
         tmpPkg.foo = "bar";
         fs.writeFileSync('./new/path/to/manifest.json', JSON.stringify(tmpPkg,null,2));
    });
    
    0 讨论(0)
  • 2021-02-04 07:31

    Grunt gives its own api for reading and writing files, i feel that better than other dependencies like fs: Edit/update json file using grunt with command grunt updatejson:key:value after putting this task in your gruntjs file

    grunt.registerTask('updatejson', function (key, value) {
            var projectFile = "path/to/json/file";
    
    
            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
    
            project[key]= value;//edit the value of json object, you can also use projec.key if you know what you are updating
    
            grunt.file.write(projectFile, JSON.stringify(project, null, 2));//serialize it back to file
    
        });
    
    0 讨论(0)
  • 2021-02-04 07:32

    I disagree with the other answers here.

    1) Why use grunt.file.write instead of fs? grunt.file.write is just a wrapper for fs.writeFilySync (see code here).

    2) Why use fs.writeFileSync when grunt makes it really easy to do stuff asynchronously? There's no doubt that you don't need async in a build process, but if it's easy to do, why wouldn't you? (It is, in fact, only a couple characters longer than the writeFileSync implementation.)

    I'd suggest the following:

    var fs = require('fs');
    grunt.registerTask('writeManifest', 'Updates the project manifest', function() {
        var manifest = require('./path/to/manifest'); // .json not necessary with require
        manifest.fileReference = '/new/file/location';
        // Calling this.async() returns an async callback and tells grunt that your
        // task is asynchronous, and that it should wait till the callback is called
        fs.writeFile('./path/to/manifest.json', JSON.stringify(manifest, null, 2), this.async());
    
        // Note that "require" loads files relative to __dirname, while fs
        // is relative to process.cwd(). It's easy to get burned by that.
    });
    
    0 讨论(0)
提交回复
热议问题