How to add an automatically generated list of files to a directory in a JS file?

I am writing an online game in HTML5. One of the files contains a list of resources located in the folder resources/img/. Now I would like this list to be automatically generated based on the contents of this folder, instead of manually updating it every time I add a new image. I'm sure Grunt can do this, but I don’t know how to configure it correctly. What to do to make Grunt generate something like this?

resources = ['a.jpg', 'b.png', 'subfolder/c.png'];
+4
source share
3 answers

I did something similar to what Jakell suggested, but I decided to use globe templates (as Florian F. suggested). I added a new Grunt task:

var fs = require("fs");
grunt.registerTask("filelist", "Lists files in a directory as JSON string to file", function() {
    var list,
        done = this.async(),
        output = grunt.config("filelist.images.output"),
        outputVariable = grunt.config("filelist.images.outputVariable"),
        patterns = grunt.config("filelist.images.patterns"),
        headerComment = '/* This file was auto-generated using Grunt task `filelist`. */\n';

    list = grunt.file.expand(patterns);

    fs.writeFile(output,
        headerComment + outputVariable + ' = ' + JSON.stringify(list) + ';',
        function (err) {
            if (err) {
                throw err;
            }
            grunt.log.writeln("List of " + list.length + " files saved to " + output);
            done();
        });
});

:

    filelist: {
        images: {
            output: "app/generated/image-list.js",
            outputVariable: "game.imageList",
            patterns: ["app/resources/img/**/*"],
        },
    },

, <script>, JS. , !:)

0

ng-boilerplate - .

script stylesheets

<!-- compiled CSS --><% styles.forEach( function ( file ) { %>
<link rel="stylesheet" type="text/css" href="<%= file %>" /><% }); %>

<!-- compiled JavaScript --><% scripts.forEach( function ( file ) { %>
<script type="text/javascript" src="<%= file %>"></script><% }); %>

grunt

return grunt.template.process( contents, {
  data: {
    scripts: jsFiles,
    styles: cssFiles,
    version: grunt.config( 'pkg.version' )
  }
});

ng- , Globbing API- grunt.file

+3

. , Node API . - :

grunt.registerTask("filelist", "Lists files in a directory as JSON string to file", function() {
    var list,
        done = this.async(),
        filename = grunt.config("filelist.images.filename"),
        directory = grunt.config("filelist.images.directory");

    list = fs.readdirSync(directory);

    fs.writeFile(filename, JSON.stringify(list), function (err) {
        if (err) { throw err; }
        grunt.log.writeln("file list from " + directory + " saved to " + filename);
        done();
    });

});

:

filelist: {
    images: {
        filename: "image.json",
        directory: "images"
    }
}

:

var fs = require("fs");

And call it that:

grunt filelist:images
+1
source

All Articles