diff options
| author | Ben Beltran <ben@nsovocal.com> | 2016-05-09 00:30:22 -0500 |
|---|---|---|
| committer | Ben Beltran <ben@nsovocal.com> | 2016-05-09 00:30:22 -0500 |
| commit | c7b4bd19a006d61c3b4979e884370d123cec7524 (patch) | |
| tree | 6be738bd4641e2fd2ab8a754dc529e773c220d64 /lib/util.js | |
| parent | ae6dbe43bf54581dd7012f95581d4a1b6ee245f0 (diff) | |
Ports the basic script to split modules
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; |