-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserve_contents.js
88 lines (69 loc) · 2.32 KB
/
serve_contents.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
const join = require('path').join;
const fs = require('fs');
const tempalteGlobals = require('../config').tempalteGlobals;
const lib = {};
const interpolate = (str, data) => {
str = typeof(str) === 'string' && str.length > 0 ? str : '';
data = typeof(data) === 'object' && data !== null ? data : {};
for (let keyName in tempalteGlobals) {
if (Object.prototype.hasOwnProperty.call(tempalteGlobals, keyName)) {
data['global.' + keyName] = tempalteGlobals[keyName];
}
}
for (let key in data) {
if (Object.prototype.hasOwnProperty.call(data, key) && typeof(data[key]) === 'string') {
str = str.replace('{' + key + '}', data[key]);
}
}
return str;
};
lib.getTemplate = function(templateName, data, cb) {
templateName = typeof(templateName) === 'string' && templateName.length > 0 ? templateName : false;
data = typeof(data) === 'object' && data !== null ? data : {};
if (templateName) {
const templateDir = join(__dirname, '/../templates/');
fs.readFile(templateDir + templateName + '.html','utf8', (err, str) => {
if (!err && str && str.length > 0) {
str = interpolate(str, data);
cb(false, str);
} else {
cb("No template could be found.");
}
});
} else {
cb('A valid template name was not defined.');
}
};
lib.addUniversalTemplates = (str, data, cb) => {
str = typeof(str) === 'string' && str.length > 0 ? str : '';
data = typeof(data) === 'object' && data !== null ? data : {};
lib.getTemplate('_header', data, (err, headerString) => {
if (!err && headerString) {
lib.getTemplate('_footer', data, (err, footerString) =>{
if (!err && footerString) {
cb(false, headerString + str + footerString);
} else {
cb('Could not find the footer template.');
}
});
} else {
cb('Could not find the header template.');
}
});
};
lib.getStaticAsset = (fileName, cb) => {
fileName = typeof(fileName) === 'string' && fileName.length > 0 ? fileName : '';
if (fileName) {
const publicDir = join(__dirname, '../public/');
fs.readFile(publicDir + fileName, (err, data) => {
if (!err && data) {
cb(false, data);
} else {
cb('No file could be found.');
}
});
} else {
cb('A valid filename was not specified.');
}
};
module.exports = lib;