Lindenk
Lindenk

Reputation: 502

Initializing client javascript variables from nodejs

I am trying to send some extra data to a client using nodejs at the same time the server is sending html and/or javascript. I'm pretty new to web development and am probably overlooking some core concept.

Here's essentially what I would like to do.

require('http');

var someVar = 'Some data';

http.createServer(function(req, res){
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.write(someWebPage);

    res.sendThisDataToClient(someVar);

    res.end();
}).listen(4000);

And the client

var someVar = getDataSentWithThisPage();
// Do stuff

I did find a way to solve the specific problem I had in a different way although I would still like to know how to do this / if it is possible / if it is the javascript way.

Upvotes: 0

Views: 393

Answers (1)

Joe Minichino
Joe Minichino

Reputation: 2773

You could use a templating engine and send your data like so:

res.render('index.html', { myVar : someVar }):

and in your index.html you'd have some expression evaluating myVar, for example <% myVar %> in ejs, or something like span=myVar in jade.

Upvotes: 1

Related Questions