2014-09-13 128 views
1

我正在使用我的buildscript,我需要更新YAML中的值(準確地說是.yml)文件。Grunt:更新YAML文件中的值?

爲了便於開發,我只是把它定義爲我的默認任務:

grunt.registerTask('default', function() { 
    var conf = grunt.file.readYAML('config.yml'); 

    // Shows correct contents of config.yml 
    console.log(conf); 

    // Changing the value of key 'deploy' 
    conf['deploy'] = 'Hello World'; 

    // Trying to write the updated data back to file 
    grunt.file.write('config.yml', conf); 

    // Re-reading the new file 
    var conf2 = grunt.file.readYAML('config.yml'); 

    // logs [ 'object Object' ] 
    console.log(conf2); 
}); 

我覺得我的意見作出很清楚什麼,我試圖做的 - 更新配置設置。

[ 'object Object' ]正在被記錄的原因是因爲它實際上是寫入該文件。這意味着我不能簡單地做grunt.file.write('config.yml', conf);,我需要類似JSON.stringify但是對於YAML。有這樣的事情存在嗎?如何更新Grunt中的yml文件中的值?

回答

5

比如這個:

https://www.npmjs.org/package/yamljs

你可以這樣做:

YAML = require('yamljs'); 
grunt.file.write('config.yml', YAML.stringify(conf)); 
+0

哇,這是比較容易,我認爲。謝謝! – Sven 2014-09-13 19:40:24