Home > Net >  How to attach a stylesheet to the output of res.write from node js?
How to attach a stylesheet to the output of res.write from node js?

Time:07-30

I have a node js program which does some stuff and outputs an html table via res.write(); The page is not connected to an html page but is just me viewing the localhost port. Since I don’t have a connected html page I was wondering where I need to link my stylesheet.

function func(){
  app.get('/', function (reqs, resp) {
  resp.writeHead(200, {'Content-Type': 'text/html'});
   resp.write("<table></table>");
   resp.end();
  });
}

var server = app.listen(8081, function () {
   func();
});

This is the relevant part of my code, where and how would I add the stylesheet?

CodePudding user response:

It's unusual, but any way you output it, HTML is still HTML. You'd use a <link> element to connect an external stylesheet. For example:

resp.writeHead(200, {'Content-Type': 'text/html'});
resp.write('<link rel="stylsheet" type="text/css" href="/url/to/your/stylesheet">');
resp.write("<table></table>");
resp.end();

Note the use of single-quotes around the whole string since it contains double-quotes.

Alternatively, if you don't have a hosted stylesheet and just want to output CSS directly to the page, that would be a <style> element. For example:

resp.writeHead(200, {'Content-Type': 'text/html'});
resp.write(`<style type="text/css">
  body {
    color: blue;
  }
  </style>`);
resp.write("<table></table>");
resp.end();

Of course you'd put whatever actual CSS styling rules you want in there. Note the use of back-ticks for a template literal instead of quotes for a plain string. This allows it to be multi-line for readability.

  • Related