Skip to content

Commit

Permalink
added support for BOM in load() and loadSync()
Browse files Browse the repository at this point in the history
  • Loading branch information
midknight41 committed Oct 3, 2013
1 parent 6258914 commit 29f1ca2
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 3 deletions.
15 changes: 12 additions & 3 deletions lib/nconf/stores/file.js
Expand Up @@ -97,7 +97,12 @@ File.prototype.load = function (callback) {
}

try {
self.store = self.format.parse(data.toString());
//deals with string that include BOM
stringData = data.toString();

if (stringData.charAt(0) === '\uFEFF') stringData = stringData.substr(1);
self.store = self.format.parse(stringData);

}
catch (ex) {
return callback(new Error("Error parsing your JSON configuration file: [" + self.file + '].'));
Expand Down Expand Up @@ -125,8 +130,12 @@ File.prototype.loadSync = function () {
// Else, the path exists, read it from disk
//
try {
data = this.format.parse(fs.readFileSync(this.file, 'utf8'));
this.store = data;
//deals with file that include BOM
fileData = fs.readFileSync(this.file, 'utf8');
if (fileData.charAt(0) === '\uFEFF') fileData = fileData.substr(1);

data = this.format.parse(fileData);
this.store = data;
}
catch (ex) {
throw new Error("Error parsing your JSON configuration file: [" + self.file + '].');
Expand Down
48 changes: 48 additions & 0 deletions test/stores/file-store-test.js
Expand Up @@ -47,6 +47,54 @@ vows.describe('nconf/stores/file').addBatch({
assert.match(err, /malformed\.json/);
}
}
},
"with a valid UTF8 JSON file that contains a BOM": {
topic: function () {
var filePath = path.join(__dirname, '..', 'fixtures', 'bom.json');
this.store = store = new nconf.File({ file: filePath });
return null;
},
"the load() method": {
topic: function () {
this.store.load(this.callback);
},
"should load the data correctly": function (err, data) {
assert.isNull(err);
}
},
"the loadSync() method": {
topic: function () {
this.store.loadSync();
return null;
},
"should load the data correctly": function (result) {
assert.isNull(result);
}
}
},
"with a valid UTF8 JSON file that contains no BOM": {
topic: function () {
var filePath = path.join(__dirname, '..', 'fixtures', 'no-bom.json');
this.store = store = new nconf.File({ file: filePath });
return null;
},
"the load() method": {
topic: function () {
this.store.load(this.callback);
},
"should load the data correctly": function (err, data) {
assert.isNull(err);
}
},
"the loadSync() method": {
topic: function () {
this.store.loadSync();
return null;
},
"should load the data correctly": function (result) {
assert.isNull(result);
}
}
}
}
}).addBatch({
Expand Down

0 comments on commit 29f1ca2

Please sign in to comment.