简体   繁体   English

使用Express和Node将json文件发送到哈巴狗模板

[英]Send a json File to a pug template with Express and Node

Forgive me but Im still a bit new to express. 原谅我,但我还是有点陌生​​。 I have a pug template running a simple homepage. 我有一个运行简单主页的帕格模板。 On the same server I have a json file containing a lists of events. 在同一台服务器上,我有一个包含事件列表的json文件。 I want to send the data in this json file to the pug template and iterate over it in a div. 我想将此json文件中的数据发送到pug模板,并在div中对其进行迭代。 I have used fs to load the file, lodash map to map it to an array. 我已经使用fs加载文件,lodash map将其映射到数组。 I have created the route for the pug file but I don't know how to link the two together ie pass the array created in my fs function to the jade route. 我已经为pug文件创建了路由,但是我不知道如何将两者链接在一起,即将在fs函数中创建的数组传递给jade路由。 I have the below so far 到目前为止我有以下

var file = __dirname + '/events.json';
fs.readFile(file, 'utf8', function (err, data) {
if (err) {
  console.log('Error: ' + err);
  return;
}

var data = JSON.parse(data);

var newEventList = data.events.map(events => ({
    id: events.id ,
    name: events.name ,
    venue: events.place.name ,
    address: events.place.location.street + " " + events.place.location.city + " " + events.place.location.zip ,
    coverPicture: events.coverPicture ,
    description: events.description ,
    startTime: events.startTime ,
    endTime: events.endTime
 }));
});


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

Can anybody point me in the right direction? 有人能指出我正确的方向吗? At the moment I get 此刻我得到

ReferenceError: newEventList is not defined

So I guess I need a way to make the route see the newEventList array. 所以我想我需要一种使路由看到newEventList数组的方法。 Thank you. 谢谢。

What you're doing isn't working because: 您正在执行的操作无效,原因是:

a) You don't do anything with the data argument within your callback to readFile a)您对readFile的回调不使用data参数做任何事情

b) node.js is asynchronous and so the parsing of the data and also app.get will run before your callback has finished anyway b)node.js是异步的,因此无论如何,在解析完成之前都会运行数据以及app.get的解析

A nice easy solution would be to just replace all of this: 一个很好的简单解决方案是仅替换所有这些:

var file = __dirname + '/events.json';
fs.readFile(file, 'utf8', function (err, data) {
if (err) {
  console.log('Error: ' + err);
  return;
}

with

var data = require('./events.json') 

which will run synchronously, so that the variable data is always available. 它将同步运行,以便变量data始终可用。

alternatively, if you want to use fs for any reason (for practice and your understanding or whatever), you will need to do all of that within the callback to app.get('/') . 或者,如果您出于任何原因(出于实践和您的理解或其他目的)要使用fs ,则需要在app.get('/')的回调中完成所有操作。 And assign the data you get back to a variable inside the callback. 并指定你回到回调内部变量的数据。

Hope that makes sense? 希望这有意义吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM