Using Jquery inject data to my plain html file from node.js , seems like not working on client side, but my console is working

StackOverflow https://stackoverflow.com/questions/21694283

  •  09-10-2022
  •  | 
  •  

Question

Mostly from internet's online, node.js user when they try to implement or inject data from node to client side (.html) is using jade framework, what if i didn't use jade framework, i need use plain html and i need inject my own data using jQuery in node.js? like,jquery's append(),html() function? Below is my code trying to use html to change client site's html, console is updated, but when i go to my web page, is still show me the old text 'yo' instead updated text 'new-text'.

var express = require("express");
var app = express();
var port = 3700;
var jsdom = require('jsdom')


app.get("/", function(req, res){
    var env = require('jsdom').env;

    env('./index.html', function (errors, window) {
        var $ = require('jquery')(window);
        console.log($('#header').text());
        $('#header').html('new-text');
        console.log($('#header').text());
    });

    res.sendfile('./index.html');

});

app.listen(port);

And here is the plain html that I'm using

<!doctype html>
<html>
<body>
<title>Test</title>
<script type="text/javascript">
</script>
</body>
<h1 id="header">yo</h1>
<p id="paragraph">lorem</p>
</html>
Was it helpful?

Solution

The code in the question is not doing what you think it is doing, because:

  1. jsdom won't modify your ./index.html file.

  2. Even if jsdom did modify your file, jsdom.env is asynchronous so you'd still be sending the file from before the change.

What you could do is change your code to send a serialized version of the DOM you modified. The following code changes the text and serves it to the client:

env('./index.html', function (errors, window) {
    var $ = require('jquery')(window);
    $('#header').html('new-text');
    res.write($("html")[0].outerHTML);
    res.end();
});

Note that the code above is meant to illustrate what a solution could look like. It is not meant to be used as-is in production.

A final note: using jsdom and jQuery to perform the task you are doing seems extremely "heavy" to me. A templating system which is designed for generating templates on the fly for the purpose of producing HTTP responses would most likely be faster than using jsdom + jQuery.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top