Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
var fs = require('graceful-fs'),
crypto = require('crypto'),
path = require('path');
// compute the sha1 hash of the file
function hashFile(name, cb)
{
var hash = crypto.createHash('sha1'),
stream = fs.createReadStream(name);
stream.on('data', function (data) {
hash.update(data);
});
stream.on('end', function () {
cb(hash.digest('hex'));
});
}
// find all non-directory files
var files = fs.readdirSync('.');
var chans = files.filter(function(f) {
return !(fs.statSync(f).isDirectory());
});
// if we're not hashing every file, filter them
if(process.argv[2] != 'all')
{
chans = chans.filter(function(f) {
// only hash the files that have filenames that don't appear to be hashes (not 32-char long hex)
return !(/^[0-9a-f]{32}.\w{3,4}/.test(f));
});
}
// if no files, don't do anything
if(chans.length == 0)
{
console.log('no files');
process.exit(0);
}
console.log('found ' + chans.length + ' files');
var numComplete = 0;
function complete()
{
console.log(numComplete + ' files done');
process.exit(0);
}
// hash each file
chans.forEach(function(f) {
var ext = path.extname(f);
hashFile(f, function(hash) {
// if nothing changed, don't do anything
if(hash + ext == f)
{
console.log(hash + ext + ', no changes made.');
numComplete++;
if(numComplete >= chans.length)
complete();
}
// if the new filename exists (there's a duplicate), don't do anything
else if(fs.existsSync(hash + ext))
{
numComplete++;
console.log(f + ' -> ' + hash + ext + ' failed, file exists');
if(numComplete >= chans.length)
complete();
}
// rename the file to the hash
else
{
fs.rename(f, hash + ext, function(e) {
if(e) throw e;
numComplete++;
console.log(f + ' -> ' + hash + ext);
if(numComplete >= chans.length)
complete();
});
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment