I want to write a grunt file so that when a file is added to a image
folder, grunt will trigger the following nodejs image resize module GruntHandler
, passing in the path to the newly added file.
Has anyone had any experience with this?
I am somewhat lost here as how to set it all up and write the grunt file to do this.
This is the code I want to trigger.
// 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!");
};
Aucun commentaire:
Enregistrer un commentaire