2

I was looking for how to get a base url for an HTML page, so that relative url requests from the browser use that base.

Here is the answer Defining root of HTML in a folder within the site root folder

When rendering the HTML from the server - is there a reliable way to add a <base> element to the HTML?

The HTML file is auto-generated, and I do not want to manually add the <base> tag to the file, if I can avoid it. It would be nice to add it dynamically somehow, when the page gets rendered.

So here is the HTML as it stands:

<head>
    <title>Code coverage report for All files</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="prettify.css" />
    <link rel="stylesheet" href="base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style type='text/css'>
        .coverage-summary .sorter {
            background-image: url(sort-arrow-sprite.png);
        }
    </style>
</head>

I want to add a base tag when rendering with the server, so it would look like:

<head>
    <title>Code coverage report for All files</title>
    <meta charset="utf-8" />
    <base href="http://localhost:3050/coverage/lcov-report/cdt-now/index.html">  // <<<<
    <link rel="stylesheet" href="prettify.css" />
    <link rel="stylesheet" href="base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style type='text/css'>
        .coverage-summary .sorter {
            background-image: url(sort-arrow-sprite.png);
        }
    </style>
</head>

The problem I suppose is that the index.html file is not at the root of my project:

enter image description here

But the index.html file makes relative path requests as you can see with the <link> tags in the <head> above.

I am currently rendering the page like this:

router.get('/', ac.allow('Admin'), function (req, res, next) {

  let html = path.resolve(__dirname + '/../coverage/lcov-report/cdt-now/index.html');

  res.setHeader('content-type', 'text/html');
  fs.createReadStream(html).pipe(res);

});
Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

1 Answers1

0

So the way to do this, using my current code which streams the response to the browser, would be:

    const replacestream = require('replacestream');

    router.get('/', ac.allow('Admin'), function (req, res, next) {

      let html, val = 'coverage/lcov-report/cdt-now/index.html';

      try {
        html = path.resolve(__dirname + `/../${val}`);
        fs.existsSync(html)
      }
      catch (err) {
        return next(err);
      }

      res.setHeader('content-type', 'text/html');
      let replacement = `</title><base href="http://localhost:3050/${val}">`;

      fs.createReadStream(html).pipe(replacestream('</title>', replacement)).pipe(res);

    });

that is the basic idea.

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817