在Grunt任务中使用节点模块失败 [英] Using a node module within a Grunt Task fails

查看:131
本文介绍了在Grunt任务中使用节点模块失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



正在执行: node test.js 这个档案:

  var exif = require('exif2'); 

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

生成预期的输出



执行grunt进程: grunt projectJSON

  module.exports = function(grunt){
var exif = require('exif2');
return grunt.registerMultiTask(projectJSON,创建项目JSON文件,function(){
exif('fixtures / forest.png',function(err,o){
console.log(arguments);
});
});

}

**注意,我只是用 fixtures / forest.png 文件



不产生任何输出。这个回调甚至没有被解雇。



当我使用console.log exif时,我得到:[Function]



我错过了什么?我认为这不起作用是因为任务繁重,但我不知道如何解决它。将它包装在try-catch块中不会产生任何结果。

解决方案

您需要使 projectJSON 任务异步 - Grunt在调用exif回调之前退出。



查看关于异步任务的Grunt文档



这就是你如何使任务异步:

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

grunt.registerMultiTask(projectJSON,创建项目JSON文件,function(){
//使任务异步
var done = this.async() ;

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

//调用任务回调继续
//其他Grunt任务
done();
});
});

}


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.

解决方案

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

}

这篇关于在Grunt任务中使用节点模块失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆