0

I'm trying to do what should be the simplest process of passing a variable to an ejs template to display in the browser.

I read a file that contains only one string and assign the output to a variable. This works fine and i can view the contents with console.log. However, i can't figure out how to code the app.get and res.render part to send that variable to ejs (index.ejs).

var fs = require('fs');

// Read the contents of the file into memory.
fs.readFile('testfile.txt', function (err, log) {

// If an error occurred, throwing it will
  // display the exception and end our app.
  if (err) throw err;

// log is a Buffer, convert to string.
  var text = log.toString();
        console.log('The content of the log is' + text);
});

// index page
app.get('/', function(req, res) {
    res.render('index', { var:  text }
    });

app.listen(8080);
console.log('8080 port');

Thanks.

Guy Lacroix
  • 41
  • 1
  • 6
  • The problem is that `readFile()` is an asynchronous method, so your `app.get()` is running before the `readFile()`. You can read about using values from async methods [here](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). – Saad Dec 01 '15 at 03:08
  • As a side note, you shouldn't be using keywords like `var` in the object that you pass. Also, you are missing a closing parentheses on your `res.render`. – Saad Dec 01 '15 at 03:16
  • Thanks for your analysis and your suggestions. So i fixed the code (missing parentheses on the res.render) and changed it to use the synchronous code below. However, there is still an issue with the rendering. Either my ejs file is wrong but i suspect it is the res.render: >> 14|

    <%= text %>

    15| 16| 17| text is not defined How do i render my "text" variable and make it show up via ejs?
    – Guy Lacroix Dec 02 '15 at 01:16
  • Change `{ var: text }` to `{ text: text }` – Saad Dec 02 '15 at 04:33

1 Answers1

0

You could read the file synchronously using readFileSync in nodejs

    var fs = require('fs');

// Read the contents of the file into memory.
var text = fs.readFileSync('testfile.txt').toString()

// index page
app.get('/', function(req, res) {
    res.render('index', { var:  text });
});

app.listen(8080);
console.log('8080 port');
Rahul Pal
  • 476
  • 3
  • 10