我想编写一个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!");
};
答案 0 :(得分:1)
您可以使用grunt-contrib-watch。添加新文件时应调用监视事件(如果监视不起作用,您可能会遇到此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);
});