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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18824071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:21:04  来源:igfitidea点击:

create a custom grunt task for processing files

javascriptgruntjs

提问by elewinso

I am trying to write a grunt task that would go over a set of input files and run a transformation on each file. let's assume the input files are given by *.inand for each of them the task will create an .outfile.

我正在尝试编写一个 grunt 任务,该任务将遍历一组输入文件并对每个文件运行转换。让我们假设输入文件是由输入文件给出的,*.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?

知道怎么做吗?

回答by elewinso

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