我的HTML模板太长了所以我决定将它们放在一个单独的文件中(我使用Babel.js):
template.js:
exports.contents = function(data) {
return `<html>
<head>
<title>Book name</title>
</head>
<body>
<h2>${data}</h2>
</body>
</html>`
}
在这里使用:
app.js:
fs.readFile(filename, 'utf8', (err, data) => {
// I'm converting Markdown to HTML. In this case the
// the file just has the text: This is some data
let result = convertToHTML(data)
fs.writeFile("untitled.html", result, (err) => {
if (err) {
console.log(err)
} else {
console.log(result)
console.log(template.contents(result))
}
})
})
console.log(result)
输出正确的结果:
<p>This is some data</p>
但是console.log(template.contents(result))
输出了这个:
<html>
<head>
<title>Book name</title>
</head>
<body>
<h2>undefined</h2>
</body>
</html>
这里发生了什么?
修改
这是convertToHTML功能:
function convertToHTML(markdownSource) {
let data = markdownSource.split(/\n\n|^>(?!.)/gm)
, orig = data.slice()
, conversions = [ convertHeadings, convertQuotes, convertDashes,
convertStyling, convertParagraphs ]
// use an original copy so the match comparison is always clean
for (let i = 0, l = orig.length; i < l; ++i) {
for (let conversion of conversions) {
let result = conversion(data[i], orig[i], orig[i - 1])
if (result !== undefined) {
data[i] = result
}
}
}
return data.join('\n\n')
}
答案 0 :(得分:4)