Grunt触发nodejs模块并传入参数

Grunt trigger nodejs module and pass in parameter

我想写一个grunt文件,这样当一个文件被添加到image文件夹时,grunt会触发下面的nodejs图像调整模块GruntHandler,传入新的路径添加文件。

有没有人有这方面的经验?

我在这里有些迷茫,不知道如何设置它并编写 grunt 文件来执行此操作。

这是我要触发的代码。

// dependencies
var async = require('async');
var gm = require('gm').subClass({ imageMagick: true });
var util = require('util');
var fs = require("fs");

var _800px = {
    width: 800,
    destinationPath: "large"
};

var _500px = {
    width: 500,
    destinationPath: "medium"
};

var _200px = {
    width: 200,
    destinationPath: "small"
};

var _45px = {
    width: 45,
    destinationPath: "thumbnail"
};

var _sizesArray = [_800px, _500px, _200px, _45px];

var len = _sizesArray.length;

// handler for dev environment

exports.GruntHandler = function (event, context) {
    // Read options from the event.
    console.log("Reading options from event:\n", util.inspect(event, {depth: 5}));

    var srcFile = event; // file being sent by grunt ---> string url to file

    var dstnFile = "/dst";

    // Infer the image type.
    var typeMatch = srcFile.match(/\.([^.]*)$/);
    if (!typeMatch) {
        console.error('unable to infer image type for key ' + srcFile);
        return;
    }
    var imageType = typeMatch[1];
    if (imageType != "jpg" && imageType != "png") {
        console.log('skipping non-image ' + srcFile);
        return;
    }

    // Download the image from S3, transform, and upload to same S3 bucket but different folders.
    async.waterfall([
            function download(next) {
                // Read the image from local file and pass into transform.

                fs.readFile(srcFile, function (err, data) {
                    if (err) {
                        next(err);
                    }
                    next(data);
                });
            },

            function transform(response, next) {


                for (var i = 0; i<len; i++) {

                    // Transform the image buffer in memory.
                    gm(response.Body, srcFile)
                        .resize(_sizesArray[i].width)
                        .toBuffer(imageType, function(err, buffer) {
                            if (err) {
                                next(err);

                            } else {
                                next(null, response.ContentType, buffer);
                            }
                        });
                }
            },

            function upload(contentType, data, next) {

                for (var i = 0; i<len; i++) {

                    // Stream the transformed image to a different folder.
                    fs.writeFile(dstnFile + "/" + _sizesArray[i].destinationPath + "/" + fileName, function (err, written, buffer) {
                        if (err) {
                            next(err);
                        }
                    });
                }
            }

        ], function (err) {
            if (err) {
                console.error(
                    '---->Unable to resize ' + srcFile +
                    ' and upload to ' + dstnFile +
                    ' due to an error: ' + err
                );
            } else {
                console.log(
                    '---->Successfully resized ' + srcFile +
                    ' and uploaded to ' + dstnFile
                );
            }

            context.done();
        }
    );

   console.log(" grunt handler called!");
};

您可以使用grunt-contrib-watch for this. Watch event should get called when new file is added (If watch doesnt work, you might be running into this https://github.com/gruntjs/grunt-contrib-watch/issues/166).

在监视事件处理程序中调用您的函数,如下所示。

使用文件的相对路径代替 .GruntHandler.js。如果文件在同一目录中,您可以按以下方式使用它。

var GruntHandler = require("./GruntHandler.js").GruntHandler;

grunt.initConfig({
  watch: {
    scripts: {
      files: ['images/*.*'],
    },
  },
});

grunt.event.on('watch', function(action, filepath, target) {
  GruntHandler(filepath);
});