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!");
};
You can use 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).
Call your function in watch event handler like following.
Use relative path of your file in place of .GruntHandler.js. In case the file is in the same directory, you can use it in the following way.
var GruntHandler = require("./GruntHandler.js").GruntHandler;
grunt.initConfig({
watch: {
scripts: {
files: ['images/*.*'],
},
},
});
grunt.event.on('watch', function(action, filepath, target) {
GruntHandler(filepath);
});
Related
I want to check the percentage of file uploading in the third server.
below is my controller code.
which upload the file to third server.
BASE.APP.post('/uploadFile/:request/:file', function (req, res, next) {
//var form = new BASE.multiparty.Form();
var path = 'uploads/'+req.params.file;
var fstream = BASE.FS.createReadStream(path);
//form.on('part', function(part) {
// console.log('inside');
var url = req.usersession.webipAddress;
/* var formData = {
file: {
value: BASE.FS.createReadStream(path),
options: {
fileNameUnique: req.params.file
}
}
};
// Post the file to the upload server
BASE.request.post({url: url+'test/service/uploadFile/', formData: formData});*/
/*var form = new BASE.FormData();
form.append('fileNameUnique', req.params.file);
form.append( 'file',fstream);
*/
var formData = {
fileNameUnique: req.params.file,
file: fstream
};
var r = BASE.request.post({url: url+'test/service/uploadFile/', formData: formData}, function(err1, res1, body){
console.log('new method err' + err1);
console.log('new method' + res1);
clearInterval(tasktimeoutId);
tasktimeoutId = false;
res.send(res1);
});
var tasktimeoutId = null;
if(!tasktimeoutId){
tasktimeoutId = setInterval(function(){
console.log('interval inside');
interrupttable.findOne({ "filename": req.params.file }, function(err, thor) {
if (thor!=null)
{
console.log('null inside');
if(thor.status=='interrupt')
{
console.log('interrupt');
r.abort();
r = null;
clearInterval(tasktimeoutId);
tasktimeoutId = false;
res.send("interrupted");
//return
//next(err);
}
}
});
}, 1000);
}
});
is there any way to check the file progress in percentage. So that i can
show the progress bar in front end.
Check this repo: https://github.com/zeMirco/express-upload-progress. It should have what you are looking for :)
I have this large amount of code which gets an image from a S3 bucket, saves it to a temporary file on Lambda, resizes it to 4 different sizes, saves it into different folders according to size and them puts the images back into the s3 bucket also into different folders.
However when running on Lambda, I have to call context.done() at the end of the whole process otherwise the context will remain alive until Lambda times out.
So I need to call context.done() when upload returns for the last time.
Looking into the two options, async and promises, which would likely need less refactoring of my code to work?
// dependencies
var AWS = require('aws-sdk');
var gm = require('gm').subClass({ imageMagick: true });
var fs = require("fs");
// get reference to S3 client
var s3 = new AWS.S3();
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;
module to be exported when in production
ports.AwsHandler = function(event, context) {
// Read options from the event.
var srcBucket = event.Records[0].s3.bucket.name;
var srcKey = event.Records[0].s3.object.key;
var dstnFolder = "/tmp";
// function to determine paths
function _filePath (directory, i) {
if ( directory === false ) {
return "dst/" + _sizesArray[i].destinationPath + "/" + srcKey;
} else if ( directory === true ) {
return dstnFolder + "/" + _sizesArray[i].destinationPath + "/" + srcKey;
}
};
for ( var i = 0; i<len; i++) {
fs.mkdir("/tmp" + "/" + _sizesArray[i].destinationPath, function (err) {
if (err) {
console.log(err);
}
});
};
// Infer the image type.
var typeMatch = srcKey.match(/\.([^.]*)$/);
if (!typeMatch) {
console.error('unable to infer image type for key ' + srcKey);
return;
};
var imageType = typeMatch[1];
if (imageType != "jpg" && imageType != "png") {
console.log('skipping non-image ' + srcKey);
return;
};
function download () {
s3.getObject({
Bucket: srcBucket,
Key: srcKey
},
function (err, response) {
if (err) {
console.error(err);
}
fs.writeFile("/tmp" + "/" + srcKey, response.Body, function (err) {
transform();
})
}
);
};
function transform () {
var _Key,
_Size;
for ( var i = 0; i<len; i++ ) {
// define path for image write
_Key = _filePath (true, i);
// define sizes to resize to
_Size = _sizesArray[i].width;
// resize images
gm("/tmp/" + srcKey)
.resize(_Size)
.write(_Key, function (err) {
if (err) {
return handle(err);
}
if (!err) {
// get the result of write
var readPath = this.outname;
var iniPath = this.outname.slice(4);
var writePath = "dst".concat(iniPath);
read(err, readPath, writePath, upload);
}
});
};
};
function read (err, readPath, writePath, callback) {
// read file from temp directory
fs.readFile(readPath, function (err, data) {
if (err) {
console.log("NO READY FILE FOR YOU!!!");
console.error(err);
}
callback(data, writePath);
});
};
function upload (data, path) {
// upload images to s3 bucket
s3.putObject({
Bucket: srcBucket,
Key: path,
Body: data,
ContentType: data.type
},
function (err) {
if (err) {
console.error(err);
}
console.log("Uploaded with success!");
});
}
download();
Take a look at how they use Q in this example.
Your code will end up very similar to
download()
.then(transform)
.then(read)
.then(upload)
.catch(function (error) {
// Handle any error from all above steps
console.error(error);
})
.done(function() {
console.log('Finished processing image');
context.done();
});
You could also take a look to async and use it as they show in this other example.
I'm relatively new to node, and want to write a module that takes an image from an S3 bucket, resizes it and saves it to a temporary directory on Amazon's new Lambda service and then uploads the images back to the bucket.
When I run the code, none of my functions seem to be called (download, transform and upload). I am using tmp to create the temporary directory and graphicsMagick to resize the image.
What is wrong with my code?
I have defined the dependencies and the array outside of the module, because I have another which depends on these.
// dependencies
var AWS = require('aws-sdk');
var gm = require('gm').subClass({ imageMagick: true });
var fs = require("fs");
var tmp = require("tmp");
// get reference to S3 client
var s3 = new AWS.S3();
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;
exports.AwsHandler = function(event) {
// Read options from the event.
var srcBucket = event.Records[0].s3.bucket.name;
var srcKey = event.Records[0].s3.object.key;
var dstnKey = srcKey;
// create temporary directory
var tmpobj = tmp.dirSync();
// function to determine paths
function _filePath (directory, i) {
if (!directory) {
return "dst/" + _sizesArray[i].destinationPath + "/" + dstnKey;
} else {
return directory + "/dst/" + _sizesArray[i].destinationPath + "/" + dstnKey;
}
};
// Infer the image type.
var typeMatch = srcKey.match(/\.([^.]*)$/);
if (!typeMatch) {
console.error('unable to infer image type for key ' + srcKey);
return;
};
var imageType = typeMatch[1];
if (imageType != "jpg" && imageType != "png") {
console.log('skipping non-image ' + srcKey);
return;
};
(function resizeImage () {
function download () {
console.log("started!");
s3.getObject({
Bucket: srcBucket,
Key: srcKey
},
function (err, response) {
if (err) {
console.error(err);
}
// call transform if successful
transform (response);
}
);
};
function transform (response) {
for ( var i = 0; i<len; i++ ) {
// define path for image write
var _Key = _filePath (tmpobj, i);
// resize images
gm(response.Body, srcKey)
.resize(_sizesArray[i].width)
.write(_Key, function (err) {
if (err) {
console.error(err);
}
upLoad ();
});
}
};
function upLoad () {
for ( var i = 0; i<len; i++ ) {
var readPath = _filePath (tmpobj, i);
var writePath = _filePath (i);
// read file from temp directory
fs.readFile(readPath, function (err, data) {
if (err) {
console.error(err);
}
// upload images to s3 bucket
s3.putObject({
Bucket: srcBucket,
Key: writePath,
Body: data,
ContentType: data.type
},
function (err) {
if (err) {
console.error(err);
}
console.log("Uploaded with success!");
});
})
}
// Manual cleanup of temporary directory
tmpobj.removeCallback();
};
}());
};
Here's a partial improvement, note the use of the async library. You will have issues in upLoad() because you are firing four asynchronous calls immediately (in the for loop) and there's no easy way to know when they are all done. (well, the easy way is to rewrite the function to use the async library, like async.forEach)
// dependencies
var AWS = require('aws-sdk');
var gm = require('gm').subClass({ imageMagick: true });
var fs = require("fs");
var tmp = require("tmp");
var async = require("async");
// get reference to S3 client
var s3 = new AWS.S3();
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;
exports.AwsHandler = function(event) {
// Read options from the event.
var srcBucket = event.Records[0].s3.bucket.name;
var srcKey = event.Records[0].s3.object.key;
var dstnKey = srcKey;
// create temporary directory
var tmpobj = tmp.dirSync();
// function to determine paths
function _filePath (directory, i) {
if (!directory) {
return "dst/" + _sizesArray[i].destinationPath + "/" + dstnKey;
} else {
return directory + "/dst/" + _sizesArray[i].destinationPath + "/" + dstnKey;
}
};
// Infer the image type.
var typeMatch = srcKey.match(/\.([^.]*)$/);
if (!typeMatch) {
console.error('unable to infer image type for key ' + srcKey);
return;
};
var imageType = typeMatch[1];
if (imageType != "jpg" && imageType != "png") {
console.log('skipping non-image ' + srcKey);
return;
};
// Actually call resizeImage, the main pipeline function:
resizeImage(function(err){
// Done. Manual cleanup of temporary directory
tmpobj.removeCallback();
})
function resizeImage (callback) {
var s3obj = {
Bucket: srcBucket,
Key: srcKey
};
download(s3obj, function(response){
var gmConfigs = sizesArray.map(function(size, i){
return {
width: size.width
_Key: _filePath (tmpobj, i)
}
})
async.eachSeries(gmConfigs,
function(config, done){
transform(response, config.width, config._Key, done)
},
function(err){
if(err){
console.log(err);
} else {
upLoad();
// Further work is required to identify if all the uploads worked,
// and to know when to call callback() here
// callback();
}
})
})
}
function download (s3obj, callback) {
console.log("started!");
s3.getObject(s3obj, function (err, response) {
if (err) {
console.error(err);
}
// call transform if successful
callback(response);
});
};
function transform (response, width, _Key, callback) {
// resize images
gm(response.Body, srcKey)
.resize(width)
.write(_Key, function (err) {
if (err) {
console.error(err);
}
callback();
});
};
function upLoad () {
for ( var i = 0; i<len; i++ ) {
var readPath = _filePath (tmpobj, i);
var writePath = _filePath (i);
// read file from temp directory
fs.readFile(readPath, function (err, data) {
if (err) {
console.error(err);
}
// upload images to s3 bucket
s3.putObject({
Bucket: srcBucket,
Key: writePath,
Body: data,
ContentType: data.type
},
function (err) {
if (err) {
console.error(err);
}
console.log("Uploaded with success!");
});
})
}
};
};
I have written this non-blocking nodejs sample recursive file search code, the problem is I am unable to figure out when the task is complete. Like to calculate the time taken for the task.
fs = require('fs');
searchApp = function() {
var dirToScan = 'D:/';
var stringToSearch = 'test';
var scan = function(dir, done) {
fs.readdir(dir, function(err, files) {
files.forEach(function (file) {
var abPath = dir + '/' + file;
try {
fs.lstat(abPath, function(err, stat) {
if(!err && stat.isDirectory()) {
scan(abPath, done);;
}
});
}
catch (e) {
console.log(abPath);
console.log(e);
}
matchString(file,abPath);
});
});
}
var matchString = function (fileName, fullPath) {
if(fileName.indexOf(stringToSearch) != -1) {
console.log(fullPath);
}
}
var onComplte = function () {
console.log('Task is completed');
}
scan(dirToScan,onComplte);
}
searchApp();
Above code do the search perfectly, but I am unable to figure out when the recursion will end.
Its not that straight forward, i guess you have to rely on timer and promise.
fs = require('fs');
var Q = require('q');
searchApp = function() {
var dirToScan = 'D:/';
var stringToSearch = 'test';
var promises = [ ];
var traverseWait = 0;
var onTraverseComplete = function() {
Q.allSettled(promises).then(function(){
console.log('Task is completed');
});
}
var waitForTraverse = function(){
if(traverseWait){
clearTimeout(traverseWait);
}
traverseWait = setTimeout(onTraverseComplete, 5000);
}
var scan = function(dir) {
fs.readdir(dir, function(err, files) {
files.forEach(function (file) {
var abPath = dir + '/' + file;
var future = Q.defer();
try {
fs.lstat(abPath, function(err, stat) {
if(!err && stat.isDirectory()) {
scan(abPath);
}
});
}
catch (e) {
console.log(abPath);
console.log(e);
}
matchString(file,abPath);
future.resolve(abPath);
promises.push(future);
waitForTraverse();
});
});
}
var matchString = function (fileName, fullPath) {
if(fileName.indexOf(stringToSearch) != -1) {
console.log(fullPath);
}
}
scan(dirToScan);
}
searchApp();
I have the following nodejs code, which as is it is, gets an image from AWS, resizes it into 4 different sizes and then saves it back into the AWS bucket into separate folders. However I need to write it so that it can be run on the dev environment as well. How could I write this so that depending on the input (local file on a vagrant machine, or on the AWS server) different functions are called (what to listen to?). It is worth noting that I am using AWS's new service Lambda.
// dependencies
var async = require('async');
var AWS = require('aws-sdk');
var gm = require('gm').subClass({ imageMagick: true });
var util = require('util');
// get reference to S3 client
var s3 = new AWS.S3();
exports.handler = function(event, context) {
// Read options from the event.
console.log("Reading options from event:\n", util.inspect(event, {depth: 5}));
var srcBucket = event.Records[0].s3.bucket.name;
var srcKey = event.Records[0].s3.object.key;
var _800px = {
width: 800,
dstnKey: srcKey,
destinationPath: "large"
};
var _500px = {
width: 500,
dstnKey: srcKey,
destinationPath: "medium"
};
var _200px = {
width: 200,
dstnKey: srcKey,
destinationPath: "small"
};
var _45px = {
width: 45,
dstnKey: srcKey,
destinationPath: "thumbnail"
};
var _sizesArray = [_800px, _500px, _200px, _45px];
var len = _sizesArray.length;
console.log(len);
console.log(srcBucket);
console.log(srcKey);
// Infer the image type.
var typeMatch = srcKey.match(/\.([^.]*)$/);
if (!typeMatch) {
console.error('unable to infer image type for key ' + srcKey);
return;
}
var imageType = typeMatch[1];
if (imageType != "jpg" && imageType != "png") {
console.log('skipping non-image ' + srcKey);
return;
}
// Download the image from S3, transform, and upload to same S3 bucket but different folders.
async.waterfall([
function download(next) {
// Download the image from S3 into a buffer.
s3.getObject({
Bucket: srcBucket,
Key: srcKey
},
next);
},
function transform(response, next) {
for (var i = 0; i<len; i++) {
// Transform the image buffer in memory.
gm(response.Body, srcKey)
.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.
s3.putObject({
Bucket: srcBucket,
Key: "dst/" + _sizesArray[i].destinationPath + "/" + _sizesArray[i].dstnKey,
Body: data,
ContentType: contentType
},
next);
}
}
], function (err) {
if (err) {
console.error(
'---->Unable to resize ' + srcBucket + '/' + srcKey +
' and upload to ' + srcBucket + '/dst' +
' due to an error: ' + err
);
} else {
console.log(
'---->Successfully resized ' + srcBucket +
' and uploaded to' + srcBucket + "/dst"
);
}
context.done();
}
);
};
I would go for creating two providers(modules) i.e fsProvider and awsProvider with download, transform and upload methods. Then in handler i will decide which provider to use depending on process.end.NODE_ENV (development or production).