diff --git a/lib/key_generators/dictionary.js b/lib/key_generators/dictionary.js index 93d9b5e..37afe82 100644 --- a/lib/key_generators/dictionary.js +++ b/lib/key_generators/dictionary.js @@ -1,32 +1,28 @@ +const winston = require('winston'); const fs = require('fs'); module.exports = class DictionaryGenerator { - constructor(options, readyCallback){ - // Check options format - if (!options) throw Error('No options passed to generator'); - if (!options.path) throw Error('No dictionary path specified in options'); + constructor({ path } = {}, readyCallback){ + //check for dictionary path + if (!path){ + winston.error('No dictionary path specified in options'); + process.exit(1); + } - // Load dictionary - fs.readFile(options.path, 'utf8', (err, data) => { - if (err) throw err; + //load dictionary + if (!fs.existsSync(path)){ + winston.error(`Dictionary file "${path}" doesn't exist`); + process.exit(1); + } - this.dictionary = data.split(/[\n\r]+/); - - if (readyCallback) readyCallback(); - }); + this.dictionary = fs.readFileSync(path).toString().split(/\s+/gm); + if (readyCallback) readyCallback(); } // Generates a dictionary-based key, of keyLength words createKey(keyLength){ - let text = ''; - - for (let i = 0; i < keyLength; i++){ - const index = Math.floor(Math.random() * this.dictionary.length); - text += this.dictionary[index]; - } - - return text; + return Array(keyLength).fill().map(() => this.dictionary[ Math.floor(Math.random() * this.dictionary.length) ] ).join(''); } };