如何在 for 循环中运行 grunt 任务,同时动态更改 config 中的数据



我正在尝试在 grunt 中运行任务,它转到 URL 并将响应保存在文件中,但我希望它转到不同的 URL 并相应地制作不同的文件。所以我正在运行一个循环,并在每次迭代中更改配置中的数据。但是任务运行被附加到循环的末尾,所以当循环完成更改配置中的所有值时,它会使用配置中最新更改的值运行任务 30 次,最后只创建 1 个文件 30 次一次又一次。这是我的代码

module.exports = function(grunt){
	grunt.initConfig({
		id:0,
		http:{
			devel:{
			options: {
			  url: 'http://127.0.0.1:8000/foo/<%= id %>/'
			},
			dest: 'www/foos/foo<%= id %>.json'
			}
		}
	});
	grunt.loadNpmTasks('grunt-http');   
	grunt.registerTask("default", function(){
    for (var i = 30; i > 1; i--) {
      grunt.config.set("id", i);
      var d = grunt.config.get("id");
      grunt.log.writeln("id = "+d);
      grunt.task.run("http");
    }
  });
};

我不是 100% 确定您要做什么,但这段代码应该可以工作。您需要为要运行的每个 http 任务创建一个唯一的任务。

module.exports = function(grunt){
    grunt.initConfig({
        http:{
        }
    });
    grunt.loadNpmTasks('grunt-http');
    var http = {};
    for (var i = 5; i > 1; i--) {
        grunt.log.writeln("id = " + i);
        http['devel' + i] = {
            options: {
              url: 'http://127.0.0.1:8000/foo/' + i
            },
            dest: 'www/foos/foo' + i + '.json'
        };
    }
    grunt.config.set("http", http);
    grunt.registerTask("default", "http");
};

最新更新