Created
January 1, 2013 00:38
-
-
Save therealplato/4424201 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example code by plato demonstrating fs and async | |
// Before running this: Create a file foo.txt in the same directory as this | |
// Additionally, run npm install async | |
var async = require('async'); | |
var fs = require('fs'); | |
handleimg = function(callback){ | |
var raft={}; // to float down the waterfall | |
raft.meta = {size:50, name:"foo.txt"}; | |
async.waterfall( | |
[ | |
function(next){ | |
// Check filesize | |
if(raft.meta.size == 0){ //no file uploaded | |
next('none', raft); | |
} else if(raft.meta.size >= 5000000){ //5Mb | |
next('toobig', raft); | |
} else { | |
next(null, raft); | |
}; | |
}, | |
function(raft, next){ | |
// Check extension | |
var tmp = raft.meta.name.match(/\.[^\.]*$/); | |
if(tmp != null){ | |
var ext = tmp[0].toLowerCase(); | |
} else { | |
var ext = null; | |
}; | |
if(ext != '.jpg' | |
&& ext != '.jpeg' | |
&& ext != '.png' | |
&& ext != '.bmp' | |
&& ext != '.tif' | |
&& ext != '.tiff' | |
&& ext != '.txt') | |
{ | |
next('extension', raft); | |
} else { | |
raft.ext = ext; | |
next(null, raft); | |
}; | |
}, | |
function(raft, next){ | |
// Rename and save uploaded file | |
raft.timenow = new Date(); | |
raft.newdir = './bar/' | |
raft.newfilename = 'bar.txt'; | |
console.log('Attempting to rename '+raft.meta.path | |
+' to '+raft.newdir+raft.newfilename); | |
// Rename has trouble if from and to paths are on different disks. | |
fs.exists('./bar/', function(exists){ | |
if(exists){ | |
fs.rename(raft.meta.name, raft.newdir+raft.newfilename, function(err){ | |
if(!err){ | |
console.log('rename OK'); | |
next(null, raft); | |
} else { | |
console.log('rename fail'); | |
console.log(err); | |
next('rename',raft); | |
}; | |
}); | |
} else { | |
fs.mkdir(raft.newdir, function(err){ | |
if(!err){ | |
console.log('mkdir OK'); | |
fs.rename(raft.meta.name, raft.newdir+raft.newfilename, function(err){ | |
if(!err){ | |
console.log('rename2 OK'); | |
next(null, raft); | |
} else { | |
console.log('rename2 error:\n'+err); | |
next('rename',raft); | |
}; | |
}); | |
} else { | |
next('mkdir', raft); | |
}; | |
}); | |
}; | |
}); | |
}, | |
], | |
function(err, raft){ // final waterfall callback | |
if(!err){ | |
callback(null, raft); | |
} else { | |
console.log('Saving image failed, reason: '+err); | |
callback(err); | |
}; | |
} | |
); // end of async.waterfall | |
}; | |
handleimg(function(err, raft){ | |
console.log('Final raft:'+JSON.stringify(raft,null,2)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment