Skip to content

Commit

Permalink
No longer throws an error with empty .json data files.
Browse files Browse the repository at this point in the history
  • Loading branch information
zachleat committed Dec 7, 2022
1 parent c7fa19e commit 7c03471
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 6 deletions.
3 changes: 2 additions & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ charset = utf-8
insert_final_newline = true

[/test/stubs*/**]
insert_final_newline = unset
insert_final_newline = unset
trim_trailing_whitespace = false
14 changes: 9 additions & 5 deletions src/TemplateData.js
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,12 @@ class TemplateData {
} catch (e) {
// if file does not exist, return nothing
}

// Can return a buffer, string, etc
if (typeof rawInput === "string") {
return rawInput.trim();
}

return rawInput;
}

Expand All @@ -483,6 +489,7 @@ class TemplateData {
let processAsTemplate = !ignoreProcessing && engineName !== false;

let rawInput;

if (readFile || processAsTemplate) {
rawInput = await this._loadFileContents(path, options);
}
Expand Down Expand Up @@ -531,11 +538,7 @@ class TemplateData {
async getDataValue(path, rawImports, ignoreProcessing) {
let extension = TemplatePath.getExtension(path);

if (
extension === "js" ||
extension === "cjs" ||
(extension === "json" && (ignoreProcessing || !this.dataTemplateEngine))
) {
if (extension === "js" || extension === "cjs") {
// JS data file or require’d JSON (no preprocessing needed)
let localPath = TemplatePath.absolutePath(path);
let exists = this._fsExistsCache.exists(localPath);
Expand Down Expand Up @@ -565,6 +568,7 @@ class TemplateData {
} else if (this.isUserDataExtension(extension)) {
// Other extensions
let { parser, options } = this.getUserDataParser(extension);

return this._parseDataFile(
path,
rawImports,
Expand Down
11 changes: 11 additions & 0 deletions test/TemplateDataTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -573,3 +573,14 @@ test("eleventy.version and eleventy.generator returned from data", async (t) =>
t.is(data.deep.nested.one, "first");
t.is(data.deep.nested.two, "second");
});

test("getData() empty json file", async (t) => {
let eleventyConfig = new TemplateConfig();
let dataObj = new TemplateData(
"./test/stubs-empty-json-data/",
eleventyConfig
);

let data = await dataObj.getData();
t.deepEqual(data.empty, {});
});
2 changes: 2 additions & 0 deletions test/stubs-empty-json-data/_data/empty.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@


0 comments on commit 7c03471

Please sign in to comment.