2

I have a node.js server and a package.json file. In that file I set some variables. For exemple "version" : 3.0. I can access those variables very easily in the node.js server. (Is there a way to get version from package.json in nodejs code?)

var pjson = require('./package.json');
console.log(pjson.version);`

But how can I pass it to my js app working on the frontend? Can I create a constant.js file that is created went I start the server (only ones).

I do not want to pass the variable as an argument every time I render a page.

I use the ejs to render my pages.

Thank you for your help.

Community
  • 1
  • 1

1 Answers1

1

You could set a cookie in the initial response.

response.setHeader("Set-Cookie", ["version=3.0"])
user2524973
  • 1,087
  • 6
  • 14
  • Can I access it in js app on the frontend after ? i'm not sure I know how :( – Tristan BARDEY May 14 '15 at 19:13
  • 1
    yes, just use `document.cookie` in client-side JS code -- this gives you all your cookies in a string (separated by semicolons); just parse from there (using `split`). MDN has some good docs on document.cookie: https://developer.mozilla.org/en-US/docs/Web/API/document/cookie – user2524973 May 14 '15 at 19:17
  • I guess you could set a cookie on login or some entry point. but there is hardly any processing with a variable in your rendering `res.render('/hom', {version:currentVersion})`. This better because you dont need to worry about users altering cookies client side, its reset on every render. – Rob May 14 '15 at 20:01
  • @Rob I see want you mean. I thought about it. I didn't want to do it this way because the render recalculates the page each time, and I don't need it. I only need it to be calculated ones. – Tristan BARDEY May 15 '15 at 10:27