lord lord - 3 months ago 10
HTML Question

How to avoid building an entire HTML page in the server?

If you look at code below on the client.on method, I res.write the entire output file because I did not know how to get the message to display with the html file. Is there a similar way of doing this rather than res.writing anything? Res.write is also very slow while when I used res.send it was very fast. Is there any other way I can do this? I am fairly new to node js


You could write an HTML template, save it into a part of the file system which is accessible from the server, then return it to the HTTP client feeded with the right value.

You could write your own template engine (and use regular expressions to make the correct substitutions), or you could you use Jade for instance.

client.on('message', function(message) {
    fs.readFile('/etc/templates/message.jade', function(_, template) {
        let body = jade.compile(template)({
                       message: message.toString()

        return res.end(body);

Where message.jade might be

doctype html
        h4 Output is: #{message}