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
You need to keep in mind that there are three separate Javascript contexts in your request:
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")