【问题标题】:create a custom grunt task for processing files创建用于处理文件的自定义 grunt 任务
【发布时间】:2013-09-23 17:09:59
【问题描述】:

我正在尝试编写一个 grunt 任务,该任务将遍历一组输入文件并在每个文件上运行一个转换。假设输入文件由*.in 给出,任务将为每个文件创建一个.out 文件。

根据我的阅读,配置看起来应该是这样的

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

并且任务注册应该是:

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

我不知道如何让 grunt 向我发送文件列表并对其进行迭代。

知道怎么做吗?

【问题讨论】:

  • 基本任务不读取配置。你想创建一个多任务。在这里阅读:gruntjs.com/creating-tasks#multi-tasks
  • @Panther 感谢您的编辑。我是 SO 新手,我想了解为什么投反对票以改进我未来的提交
  • @elewinso :避免评论“谢谢/抱歉等”。而且我不确定为什么会投反对票。

标签: javascript gruntjs


【解决方案1】:

这就是我结束做的事情并解决了我的问题。 对于任务配置,我做了以下操作:

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

这是任务的实现:

  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);
    });
  });
});
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 2015-05-10
    • 1970-01-01
    • 2017-06-04
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多