Search code examples
javascriptnode.jsvariablespug

Use server generated variable in an included frontend js file


node.js beginner here. So I am writing an application where every second I get a number generated by the server and paste it via the app. Get to my index.pug file and I want to work with that number in an embed js file. How do I do that?

server.js

randomNumber = 4;
app.get('/',(req,res) => {
    res.render('index', {title: 'Number', count: randomNumber})
});

index.pug

html
 head
  title= title
 body
  h1= count
  script(src="includes/client.js")

client.js

var chart = new CanvasJS.Chart("chartContainer", { 
   title: {
    text: count
   },
});

Now how do I work with the randomNumber variable in the client.js file? What am I missing here? The application always tells me that count is not defined


Solution

  • You need to keep in mind that there are three separate Javascript contexts in your request:

    1. The route (server.js),
    2. The view/template (index.pug), and
    3. The browser

    None of the above can access any of the others unless you explicitly pass variables through to the next one in the chain.

    You are explicitly passing title and count into the view/template in the res.render statement, and to then pass them one step further into the browser you need to use unescaped string interpolation and add it into a <script> tag as follows:

    html
     head
      title= title
     body
      h1= count
      script.
        var count = !{count};
      script(src="includes/client.js")
    

    If you want count to come through as a string, define it like this instead:

    html
     head
      title= title
     body
      h1= count
      script.
        var count = "!{count}";
      script(src="includes/client.js")