added support for BOM in load() and loadSync()

master
midknight41 2013-10-03 09:17:36 +01:00
parent 62589145f3
commit 29f1ca281b
2 changed files with 60 additions and 3 deletions

View File

@ -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 + '].'));
@ -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 + '].');

View File

@ -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({