从.md或.json文件导入数据

时间:2013-11-09 09:26:40

标签: json node.js

我对nodejs感到新奇和好奇。

我想将数据从json(或.md)文件导入节点/ jade页面。只是指出方向我应该看起来没问题。

这样的东西
{
  "name": "contact_info",
  "workers": {
    "john": {
      "img": "/img/john.jpg",
      "name": "John Mitchel",
      "description": "John is a nice guy...",
    },
    "anna": {
      "img": "/img/anna.jpg",
      "name": "Anna James",
      "description": "Anna is great at tenis",
    },
... //etc

并导入它,以便在html for web中呈现。

任何指针都会受到赞赏。

1 个答案:

答案 0 :(得分:5)

您可以使用require从文件加载JSON。假设您使用express jade,则可以执行以下操作;

var express = require('express')
 , path     = require('path')
 , jade     = require('jade')

// load in JSON from a file named data.json
 , data     = require('./data');

var app = express();

app.configure(function() {

  app.set('port', process.env.PORT || 8080);

  app.engine('.jade', jade.__express);

  app.set('view engine', 'jade');
  app.set('views', path.join(__dirname, 'views'));
})

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

  // render the Jade template located in views/index.jade file passing in data
  res.render('index', {data: data});

});

 app.listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

由您在index.jade

中根据需要呈现JSON