Skip to content

Instantly share code, notes, and snippets.

@lac5
Last active June 17, 2024 15:06
Show Gist options
  • Save lac5/eb161de9144e3bd29a744c7e6354aea9 to your computer and use it in GitHub Desktop.
Save lac5/eb161de9144e3bd29a744c7e6354aea9 to your computer and use it in GitHub Desktop.
Renames files to their md5 value of their content.
const path = require('path');
const fs = require('fs').promises;
const md5 = require('md5');
const uuid = require('uuid/v5');
const argv = require('yargs')
.strict()
.usage('$0 <files...>', 'Rename files to their md5 value.', (yargs) => {
yargs.positional('files', {
describe: 'The files that will be renamed.',
type: 'array'
})
})
.option('base64', {
demand: false,
default: false,
type: 'boolean',
description: 'Use base64 instead of hexadecimal.',
})
.option('slice-left', {
demand: false,
default: 0,
type: 'number',
description: 'Trim left of the filename by X characters.',
})
.option('slice-right', {
demand: false,
default: 0,
type: 'number',
description: 'Trim right of the filename by X characters.',
})
.option('hash', {
demand: false,
default: null,
type: 'string',
description: 'Use UUID v5 instead of MD5.',
})
.alias('v', 'version')
.alias('h', 'help')
.alias('b', 'base64')
.alias('L', 'trim-left')
.alias('R', 'trim-right')
.alias('H', 'hash')
.argv;
Promise.all(argv.files.map(async file => {
try {
let fileMd5 = md5(await fs.readFile(file));
if (argv.hash) {
fileMd5 = uuid(argv.hash, fileMd5, Buffer.alloc(16)).toString('hex');
}
if (argv.base64) {
fileMd5 = Buffer.from(fileMd5, 'hex').toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '')
}
if (argv.trimLeft || argv.trimRight) {
fileMd5 = fileMd5.slice(argv.trimLeft, argv.trimRight || fileMd5.length);
}
fileMd5 += path.extname(file);
await fs.rename(file, path.join(path.dirname(file), fileMd5));
console.log('%s --> %s', file, fileMd5);
} catch (e) {
console.error(e);
}
})).then(()=> console.log('done!'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment