Error: can't find 'dust' module when rendering dust templates on node.js

Error: can't find 'dust' module when rendering dust templates on node.js

我从 express 为我生成的样板代码开始。我需要 dustjs-linkedin 并在 app.js 中编译一些简单的模板,如下所示:

var dust = require('dustjs-linkedin');...

app.set('view engine', 'dust');...

var compiled = dust.compile("Hello {name}!","intro");
// add into dust.cache manually
dust.loadSource(compiled);
console.log(dust.cache);

dust.render("intro", {name: "Fred"}, function(err, out) {
  if(err){console.log(err)}
  console.log(out);
});

一切正常,我在终端中看到 HTML 输出。仅当我开始收到此错误时,才尝试从路线中执行相同的操作:

GET / 500 11.607 ms - 904 Error: Cannot find module 'dust'

app.get('/', function(req, res){
  var compiled = dust.compile("Hello {name}!", "intro");
  dust.loadSource(compiled)
  dust.render("intro", {name: "Fred"}, function(err, out) {
    console.log(out);
    res.send(out);
    res.close();
  });
});

这一切都在 app.js 之内,只是它在路由之外起作用,但当我将它移到路由回调中时却不起作用。有谁知道为什么找不到'dust'?我需要它,它应该在回调中可见,对吗?

感谢您的帮助!

编辑 1 根据下面的评论,'dust' 在某处被要求。我没有在我的代码中这样做;我的猜测是 Express 正在幕后执行此操作,因为我的模板以“.dust”文件结尾。我刚刚尝试删除我所有的模板(无论如何都没有使用它们),现在我只收到这个错误:

Error: Failed to lookup view "error" in views directory

我只想看到输出:"Hello Fred"

编辑 2:我想我发现了什么问题

Interrobang 发布的所有内容都是正确的。我认为问题出在这个由 express-generator 为我生成的中间件块:

app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

所以对于每个请求,这个中间件都会触发并抛出错误。我不是 100% 确定它在做什么,但如果我将其注释掉,一切正常。我现在的第二个问题,如果我有的话,到底是怎么回事,为什么要为所有请求设置它?

您正在将 view engine 设置为 dust,但是您还没有向 Express 注册一个引擎来告诉它如何渲染 Dust——默认情况下 Express 不能这样做.

考虑使用 consolidate, hoffman, or adaro(以及其他)作为 Express 的 Dust 渲染引擎。

这是一个使用合并的完整示例。我已经测试过并且可以在我的机器上运行。

var express = require('express'),
    cons = require('consolidate'),
    app = express();

// assign the dust engine to .dust files 
app.engine('dust', cons.dust);

// set .dust as the default extension 
app.set('view engine', 'dust');
app.set('views', __dirname + '/views');

app.get('/', function(req, res) {
    res.render('index', { name: 'Interrobang' });
});

app.listen(3000, function () {
  console.log('Visit http://localhost:3000 woo!');
});

或者,只需从您的代码中删除 view engine 行。您没有使用 Express 进行渲染,因此 Express 甚至不需要知道。

这是一个非常简单的示例,没有我测试过的任何视图引擎。您的 Dust 模板位于名为 views.

的文件夹中
var fs = require('fs'),
    path = require('path'),
    express = require('express'),

    dust = require('dustjs-helpers');

dust.config.whitespace = true;

dust.onLoad = function(tmpl, cb) {
  fs.readFile(path.join('./views', path.resolve('/', tmpl + '.dust')),
              { encoding: 'utf8' }, cb);
};

var app = express();
app.get('/', function (req, res) {
  dust.stream("hello", { "world": "World!" }).pipe(res);
});

app.listen(3000, function () {
  console.log('Visit http://localhost:3000 woo!');
});