简体   繁体   English

创建用于处理文件的自定义grunt任务

[英]create a custom grunt task for processing files

I am trying to write a grunt task that would go over a set of input files and run a transformation on each file. 我正在尝试编写一个grunt任务,它将遍历一组输入文件并对每个文件运行转换。 let's assume the input files are given by *.in and for each of them the task will create an .out file. 假设输入文件由*.in给出,对于每个输入文件,任务将创建一个.out文件。

From what I read, it seems that the config should look something like this 从我读到的,似乎配置应该看起来像这样

grunt.initConfig({
    my_task: {
        src: 'C:/temp/*.in',
        dest: 'C:/temp/output/*.out'
    }
});

and the task registration should be: 任务注册应该是:

grunt.registerTask('my_task', 'iterate files', function() {
    //iterate files.
});

I cannot figure out how to make grunt send me the list of files and iterate over them. 我无法弄清楚如何使grunt发送给我文件列表并迭代它们。

Any idea how to do it? 知道怎么做吗?

This is what I ended doing and what solved my problem. 这就是我结束的目的,是什么解决了我的问题。 for the task configuration I did the following: 对于任务配置,我执行了以下操作:

  grunt.initConfig({
    convert_po: {
      build: {
        src: 'C:/temp/Locale/*.po',
        dest: 'C:/temp/Locale/output/'
      }
    }
  });

and this is the task's implementation: 这是任务的实现:

  grunt.registerMultiTask('convert_po', 'Convert PO files to JSON format', function() {
var po = require('node-po');
var path = require('path');

grunt.log.write('Loaded dependencies...').ok();

//make grunt know this task is async.
var done = this.async();

var i =0;
this.files.forEach(function(file) {
  grunt.log.writeln('Processing ' + file.src.length + ' files.');

  //file.src is the list of all matching file names.
  file.src.forEach(function(f){ 
    //this is an async function that loads a PO file
    po.load(f, function(_po){
      strings = {};
        for (var idx in _po.items){
            var item = _po.items[idx];
            strings[item.msgid] = item.msgstr.length == 1 ? item.msgstr[0] : item.msgstr;
        }
        var destFile = file.dest + path.basename(f, '.po') + '.json';
        grunt.log.writeln('Now saving file:' + destFile);
        fs.writeFileSync(destFile, JSON.stringify(strings, null, 4));

        //if we processed all files notify grunt that we are done.
        if( i >= file.src.length) done(true);
    });
  });
});
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM