nodejs fs打印视图源代码而不是在openshift上呈现视图

时间:2014-12-31 20:29:30

标签: node.js express openshift mustache fs

这个应用程序在本地工作正常,可以在openshift上运行,没有错误,但是视图不能呈现它只是打印源代码。我尝试删除并重新创建应用程序,但仍然没有运气。

这是我的server.js文件的一部分:

var express    = require('express');
var app        = express();
var bodyParser = require('body-parser');

var fs = require("fs");
var handlebars = require("handlebars");
var WebPageTest = require('webpagetest');

// Web Page Test - API key.
var wpt = new WebPageTest('www.webpagetest.org', '1234567890');

var router = express.Router();

app.use("/css", express.static(__dirname + '/css'));
app.use("/js", express.static(__dirname + '/js'));
app.use("/img", express.static(__dirname + '/img'));

/***** Views *****/
// Homepage.
app.get('/', function(req, res) {

  var template = fs.readFileSync("views/index.html", "utf8");

  // handlebars data, optional.
  var source = {
    message : "Homepage!"
  };

  var pageBuilder = handlebars.compile(template);
  var pageText = pageBuilder(source);
  res.writeHead(200, {"Context-Type": "text/html"});
  res.write(pageText);
  res.end();

});

/***** Start App *****/
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 5000;
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';

app.listen(server_port, server_ip_address, function(){
  console.log("Listening on " + server_ip_address + ", server_port " + server_port);
});

这是package.json

的一部分
{
  "name": "wpt",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "dependencies": {
    "body-parser": "^1.10.0",
    "express": "^4.10.6",
    "webpagetest": "^0.3.1",
    "mongoose": "^3.8.21",
    "handlebars": "^2.0.0",
    "express3-handlebars": "^0.5.2",
    "fs":"*"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },

我手动将fs添加到依赖项中,但它似乎没有任何效果。

1 个答案:

答案 0 :(得分:1)

使用诸如hbs之类的车把Express视图引擎可能要容易得多。例如:

// ...

var hbs = require('hbs');

app.engine('hbs', hbs.__express);
app.engine('html', hbs.__express);
app.set('view engine', 'hbs');
app.set('views', __dirname + '/views');
hbs.localsAsTemplateData(app);

app.get('/', function(req, res) {
  res.render('index.html', {
    message: 'Homepage!'
  });
});

// ...