Node.js: How to embed Node.js in HTML?
In php file I can do:
<p><?php echo "hello!";?></p> Is there a way to do this in node, if so, what is the logic for it?
I have an idea how to do this:
Use identifier markup for node in the HTML file, for example:
<node>code</node>Download and parse the HTML file in Node
Grab the node markup from the HTML file and run it
But I'm not sure if this is the best way or even if it works :)
Please note: I want to know node.js , so explicit and other libraries and modules are not responsible for me, because I want to know the logic of the process.
What do you describe / request node.js. preprocessor It exists , but is considered harmful.
The best solution would be to use the representations used in express. Take a look at screencasts .
If you have to do everything from scratch, you can write a mechanism for micro-templates.
function render(_view, data) { var view = render.views[view]; for (var key in data) { var value = data[key]; view.replace("{{" + key + "}}", value); } return view; } render.views = { "someView": "<p>{{foo}}</p>" }; http.createServer(function(req, res) { res.end(render("someView", { "foo": "bar" })); }); There are good reasons why poorly mixing php / asp / js code directly with HTML. This does not contribute to the separation of problems and leads to a spaghetti code. These days, engine templates like the ones described above are the standard method.
Want to know more about micro templates? Read the article by J. Resig .
You can try using JooDee, a node web server that allows you to embed JavaScript servers in your web pages. If you are familiar with node and PHP / ASP, you just need to create pages. Here is an example of what the page looks like below:
<!DOCTYPE html> <html> <: //server side code in here var os = require('os'); var hostname = os.hostname(); :> <body> <div>Your hostname is <::hostname:></div> </body> </html> Using JooDee also allows you to easily set server-side javascript vars to the client by adding attributes to the server side of the Client objects and accessing the generated Client object on the JavaScript side of your client.