为什么这个必需函数的变量参数返回undefined?

时间:2015-04-23 13:56:10

标签: javascript node.js

我的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')
}

1 个答案:

答案 0 :(得分:4)

That很简单:

console.log(result);
console.log(template.contents());

也许你想传递一些东西给你的功能? : - )