nci/lib/reader/index.js

50 lines
1.0 KiB
JavaScript
Raw Normal View History

2015-05-18 17:52:01 +00:00
'use strict';
var Steppy = require('twostep').Steppy,
_ = require('underscore'),
fs = require('fs'),
2016-01-10 13:55:57 +00:00
path = require('path');
2015-05-18 17:52:01 +00:00
2016-01-10 13:55:57 +00:00
function Reader() {
this.constructors = {};
}
exports.Reader = Reader;
2016-01-10 13:55:57 +00:00
Reader.prototype.register = function(ext, constructor) {
this.constructors[ext] = constructor;
2015-05-18 17:52:01 +00:00
};
2016-01-10 13:55:57 +00:00
Reader.prototype.load = function(dir, name, callback) {
var self = this;
2015-05-18 17:52:01 +00:00
Steppy(
function() {
fs.readdir(dir, this.slot());
},
function(err, filePaths) {
var ext;
var filePath = _(filePaths).find(function(filePath) {
ext = path.extname(filePath).replace(/^\./, '');
return (
2016-01-10 13:55:57 +00:00
ext in self.constructors &&
2015-05-18 17:52:01 +00:00
path.basename(filePath, '.' + ext) === name
);
});
if (filePath) {
2016-01-10 13:55:57 +00:00
var Constructor = self.constructors[ext],
2015-05-18 17:52:01 +00:00
reader = new Constructor();
reader.load(dir, name, this.slot());
} else {
throw new Error(
'Can`t load "' + name + '" from "' + dir + '" using ' +
2016-01-10 13:55:57 +00:00
'readers: ' + _(self.constructors).keys().join(', ')
2015-05-18 17:52:01 +00:00
);
}
},
callback
);
};