简体   繁体   中英

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. I want to send the data in this json file to the pug template and iterate over it in a div. I have used fs to load the file, lodash map to map it to an array. 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. 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. 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

b) node.js is asynchronous and so the parsing of the data and also app.get will run before your callback has finished anyway

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.

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('/') . And assign the data you get back to a variable inside the callback.

Hope that makes sense?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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