Skip to content

Commit

Permalink
Allow pointing to separate database source.
Browse files Browse the repository at this point in the history
  • Loading branch information
Jonathan Kim committed Jun 9, 2020
1 parent d24baef commit e398862
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 7 deletions.
1 change: 1 addition & 0 deletions examples/lookup.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const wordnet = require('../lib/wordnet.js');
program
.version('0.0.1')
.usage('<word>')
.option('-d, --database <database-path>', 'Location of WordNet index and data files.')
.parse(process.argv);

/* Word to look up */
Expand Down
22 changes: 15 additions & 7 deletions lib/wordnet.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,26 @@ function getKey(word) { return `${KEY_PREFIX}${word}` }
*
* @return {Promise} Empty promise object.
*/
module.exports.init = async function() {
module.exports.init = async function(databaseDir) {
const extensions = Object.keys(EXTENSIONS_MAP);

if (!databaseDir) {
databaseDir = __dirname + '/../db';
}

// Read data from all index files into memory.
// NOTE: We have to run this serially in order to ensure consistent results.
await extensions.reduce((p, ext) => {
return p.then(() => readIndex(ext));
return p.then(() => {
return readIndex(`${databaseDir}/index.${ext}`);
});
}, Promise.resolve());

// Load the contents from the data files into memory.
await Promise.all(extensions.map((ext) => {
return readDatabase(ext).then((fileHandle) => _data[EXTENSIONS_MAP[ext]] = fileHandle);
return readDatabase(`${databaseDir}/data.${ext}`).then((fileHandle) => {
_data[EXTENSIONS_MAP[ext]] = fileHandle;
});
}));

return Promise.resolve();
Expand Down Expand Up @@ -107,9 +115,9 @@ function readData(definition, skipPointers) {
});
}

function readIndex(extension) {
function readIndex(filePath) {
return new Promise((resolve) => {
reader.read(__dirname + '/../db/index.' + extension, (line) => {
reader.read(filePath, (line) => {
let result = parseIndexLine(line);

if (!result.isComment) {
Expand All @@ -130,8 +138,8 @@ function readIndex(extension) {
* @param {String} extension WordNet DB extension.
* @return {Promise} Resolves with FileHandle object.
*/
function readDatabase(extension) {
return fsp.open(__dirname + '/../db/data.' + extension, 'r');
function readDatabase(filePath) {
return fsp.open(filePath, 'r');
}

/**
Expand Down
1 change: 1 addition & 0 deletions test/wordnet.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ test('api', async (t) => {
// - Calling API functions before init.
// - Searching for a word not in the database.

// TODO: Add test for initializing with a custom path.
await wordnet.init();

let list = await wordnet.list();
Expand Down

0 comments on commit e398862

Please sign in to comment.