app.engine() 是做什么的?什么是分机和回调?

What does app.engine() do ? And what are ext and callback?

我试着通读文档,他们说

app.engine(ext, callback)

Register the given template engine callback as ext By default will require() the engine based on the file extension. For example if you try to render a "foo.jade" file Express will invoke the following internally, and cache the require() on subsequent calls to increase performance.

我很难搞清楚这里的 ext 和 callback 是什么意思。

简单来说:ext - 扩展,回调 - 将呈现具有给定扩展名的文件的库(引擎)。

这是 Express view/template 引擎 functionality 的一部分。很多时候你的请求处理程序只有 return 一些 JSON 对象。但有时您想要构建一个常规的 "document",例如完全构建的 HTML 页面或 RSS 提要等。模板引擎可以帮助您实现这一点,尽管它们绝不是强制性的。您可以使用其他方法(例如,如果您喜欢这种痛苦,可以手动构建字符串),或者您可以手动使用 pug/moustache 等库。视图引擎功能基本上将 pug/moustache 等库集成到 express 中,因此更易于使用。

链接页面有一个很好的例子,说明如何在实践中使用它:

Then create a route to render the index.pug file. If the view engine property is not set, you must specify the extension of the view file. Otherwise, you can omit it.

app.get('/', function (req, res) { res.render('index', { title: 'Hey', message: 'Hello there!' }) })

When you make a request to the home page, the index.pug file will be rendered as HTML.

多次表达对各种模板引擎的了解。所以说 express.set('view engine', 'pug') 就足够了,只要安装了 pug 包,它就可以做正确的事情。

其他时候您需要使用 app.engine 更明确地告诉它要做什么。它被称为 app.engine('jade', require('jade').__express)。第一个参数就是 express 应该寻找的扩展名。因此,当您说 req.render('index', ...) 时,它会查找 index.jade 文件。第二个参数是在视图引擎(如我所说,与 express 不同)和 express 之间实际进行集成的函数。 consolidate.js 是一个集成了很多视图引擎的包。

但如果您想查看此函数的作用,请查看 developing template engines for Expresscallback 参数必须类似于 function(filePath, options, callback)filePath 只是用于渲染的磁盘文件的名称,因此上面示例中的 index.jadecallback 是标准节点回调,在出错时调用为 callback(err) 或在成功时调用为 callback(null, renderedContent)options 是从 req.render('index.jade', /* options */ { title: 'foo', content: 'bar' }) 传入的对象。然后由您决定如何根据提供的参数实际进行渲染。