diff options
| author | Ben Beltran <ben@nsovocal.com> | 2016-05-09 00:31:52 -0500 |
|---|---|---|
| committer | Ben Beltran <ben@nsovocal.com> | 2016-05-09 00:31:52 -0500 |
| commit | a41763dd463339765081c1f968a7b93b8ccf572f (patch) | |
| tree | 131f33520cc40abc387474fa9c2ac4f536e6d7d1 /lib/util.js | |
| parent | 95da493e0ec223e1c7706fc0bdc364bd3a21d999 (diff) | |
| parent | a140f3add912ef4bd659c1c1e82184643be7d845 (diff) | |
Merge branch 'release/1.0.0'
Diffstat (limited to 'lib/util.js')
| -rw-r--r-- | lib/util.js | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/lib/util.js b/lib/util.js new file mode 100644 index 0000000..3234d3e --- /dev/null +++ b/lib/util.js @@ -0,0 +1,50 @@ +'use strict'; + +const Fs = require('fs'); +const Path = require('path'); + +// Module containing utility functions. +const Util = { + + // Parses a 16 bit number buffer. + parse16BitBuffer: function (buffer) { + return buffer[0] * 256 + buffer[1]; + }, + + // Picks a random element from an array. + pickRandom: function (array) { + return array[Math.floor(Math.random() * array.length)]; + }, + + // For a given path, requires all of the files and returns an array + // with the results. If the directory contains any non-requireable file, + // it will fail. + loadFiles: function (path) { + return new Promise(function (resolve, reject) { + Fs.readdir(path, function (err, files) { + if (err) { + return reject(err); + } + + let loadedFiles = []; + + for (let file of files) { + let filePath = Path.join(path, file); + let loadedFile; + + try { + loadedFile = require(filePath); + } catch (err) { + return reject(err); + } + + loadedFiles.push(loadedFile); + } + + resolve(loadedFiles); + }); + }); + } +}; + +module.exports = Util; |