Using a node module within a Grunt Task fails

2019-09-08 04:26发布

I'm trying to extract meta data from files read within a Grunt task.

executing: node test.js on this file:

var exif = require('exif2');

exif('fixtures/forest.png', function (err, o) {
    console.log(arguments);
});

Produces the expected output

However, executing the grunt process: grunt projectJSON

module.exports = function (grunt) {
    var exif = require('exif2');
    return grunt.registerMultiTask("projectJSON", "Creates project JSON file.", function () {
        exif('fixtures/forest.png', function (err, o) {
            console.log(arguments);
        });
    });

}

** note that I am just testing with the fixtures/forest.png file

Produces no output whatsoever. The callback isn't even fired.

When I console.log exif, I get: [Function]

What am I missing? I think that the doesn't work is because of the grunt task, but I have no idea how to fix it. Wrapping it in a try-catch block produces nothing.

1条回答
何必那么认真
2楼-- · 2019-09-08 05:21

You need to make your projectJSON task asynchronous - Grunt is exiting before your exif callback is being invoked.

Have a look at the Grunt documentation on asynchronous tasks.

This is how you can make your task asynchronous:

module.exports = function (grunt) {
    var exif = require('exif2');

    grunt.registerMultiTask("projectJSON", "Creates project JSON file.", function () {
        // Make task asynchronous.
        var done = this.async();

        exif('fixtures/forest.png', function (err, o) {
            console.log(arguments);

            // Invoke the task callback to continue with
            // other Grunt tasks.
            done();
        });
    });

}
查看更多
登录 后发表回答