据我了解,您希望合并不同的页面。
您需要开发一个函数来读取不同的文件并将它们组合在一起并将响应发送给客户端。您需要将内容类型定义为“text/html”。
示例函数:
描述:
1.阅读主页
2.读头
3. 阅读页脚
4.合并页面部分
5. 发送到响应。
// Main Object
_index = {};
// This object return content of the page
_index.get = function(data, callback) {
const templateData = {};
templateData['head.title'] = 'Page Title';
templateData['head.description'] = 'Description';
templateData['body.title'] = 'Body Title';
templateData['body.class'] = 'css-class';
// Read the main page contant.
_index.getTemplate('index', templateData, (err, str) => {
if (!err && str) {
// Read rest of the page contant and put them together.
_index.addUniversalTemplate(str, templateData, (err, str) => {
if ((!err, str)) {
callback(200, str, 'html');
} else {
callback(500, undefined, 'html');
}
});
} else {
callback(500, undefined, 'html');
}
});
// callback(undefined, undefined, 'html');
};
_index.getTemplate = (templateName, data, callback) => {
templateName =
typeof templateName == 'string' && templateName.length > 0
? templateName
: false;
if (templateName) {
const templateDir = path.join(__dirname, './../template/');
fs.readFile(templateDir + templateName + '.html', 'utf8', (err, str) => {
if (!err && str && str.length > 0) {
// Do interpolation on the data
let finalString = _index.interpolate(str, data);
callback(false, finalString);
} else {
callback('No Template could be found.');
}
});
} else {
callback('A valid template name was not specified.');
}
};
// Add the universal header and footer to a string and pass provided data object to the header and footer for interpolation.
_index.addUniversalTemplate = function(str, data, callback) {
str = typeof str == 'string' && str.length > 0 ? str : '';
data = typeof data == 'object' && data !== null ? data : {};
// Get header
_index.getTemplate('_header', data, (err, headerString) => {
if (!err && headerString) {
_index.getTemplate('_footer', data, (err, footerTemplate) => {
if (!err && footerTemplate) {
let fullString = headerString + str + footerTemplate;
callback(false, fullString);
} else {
callback('Could not find the footer template');
}
});
} else {
callback('Could not find the header template.');
}
});
};