1

I am working on node express server which generates reports (tables, charts) for data stored in database (MongoDB). What makes it hard is that the report should be downloadable as a single file and viewable offline. Which means that all the data and javascript should be inside the html file.

By searching stackoverflow I found this question - Inline CSS/Javascript into a HTML file. One of the solutions is command-line tool which visits the page and bundles together all assets, other solutions use other languages. In my case it doesn't make sense to visit the page and download the files as they are already in memory and should be imported from node server.

So here is example of how I've been doing it so far.

Server.js:

// Templating library
const mustache = require("mustache");
// Javascript to be imported into html as inline script
const someFunction = require("./src/someFunction.js").toString();

app.get("/:id", async (req, res) => {
  // Get data from DB
  const data = await MongooseSchema.find({ id: req.params.id });

  // Read html view
  const view = fs.readFileSync("./views/report.html", "utf8"});

  // Render with mustache
  const html = mustache.to_html(view, {
    data,
    javascript: { someFunction }
  });

  // Send rendered html
  res.send(html);
});

And report.html includes this script tag:

<script>
  const data = {{{data}}};
  {{{javascript.someFunction}}}
</script>

I am importing javascript files as strings and then rendering them inside the html file using mustache templating library. This approach seems kind of hacky, there should be a better way.

Also I am thinking about implementing some bundler (webpack/parcel/rollup) to combine all the js files into one which I could then manually import into html as inline script. And maybe even use some framework like react to make my life easier.

So my question is, is this approach viable? Are there any better ways to do this?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.