Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js Generate html

I have created a JavaScript program which generates a list of data. Example output below:

output one  output two  output three  ... 

I would like to be able to generate a HTML file which can be saved to disk and opened with a browser. Below is a sample of the HTML I would like to generate.

<html>     <head>     </head>     <body>         <table id="history_table">             <tr>                 <td>header 1</td>                 <td>header 2</td>                 <td>header 3</td>             </tr>             <tr>                <td>output one</td>             </tr>             ...         </table>     </body> </html> 

I have tried doing this:

var htmlDoc = document.createElement("HMTL"); htmlDoc.innerhtml('<head></head><body>...</body>'); 

But this is clearly wrong since the document object does not exist.

I think this question makes sense especially from the amount of up votes it has received. can it be reopened?

like image 443
lufthansa747 Avatar asked Feb 07 '14 01:02

lufthansa747


People also ask

CAN node JS render HTML?

Run nodemon to start the server. Whenever the server is running, and accessing the route http://localhost:3000/ , it will output the plain text hello world! . We can use the same server to render HTML elements as the server response instead of sending plain text.

Can JavaScript generate HTML?

The DOM makes it possible for programs such as JavaScript to change the document structure, style and content. The HTML elements on a page is simply a tree of nodes and objects that together provides structure for showing text, link, image, video and so forth.


1 Answers

Node.js does not run in a browser, therefore you will not have a document object available. Actually, you will not even have a DOM tree at all. If you are a bit confused at this point, I encourage you to read more about it before going further.

There are a few methods you can choose from to do what you want.


Method 1: Serving the file directly via HTTP

Because you wrote about opening the file in the browser, why don't you use a framework that will serve the file directly as an HTTP service, instead of having a two-step process? This way, your code will be more dynamic and easily maintainable (not mentioning your HTML always up-to-date).

There are plenty frameworks out there for that :

  • Http (Node native API)
  • Connect
  • koa
  • Express (using Connect)
  • Sails (build on Express)
  • Meteor
  • CompoundJS
  • etc.

The most basic way you could do what you want is this :

var http = require('http');  http.createServer(function (req, res) {   var html = buildHtml(req);    res.writeHead(200, {     'Content-Type': 'text/html',     'Content-Length': html.length,     'Expires': new Date().toUTCString()   });   res.end(html); }).listen(8080);  function buildHtml(req) {   var header = '';   var body = '';    // concatenate header string   // concatenate body string    return '<!DOCTYPE html>'        + '<html><head>' + header + '</head><body>' + body + '</body></html>'; }; 

And access this HTML with http://localhost:8080 from your browser.

(Edit: you could also serve them with a small HTTP server.)


Method 2: Generating the file only

If what you are trying to do is simply generating some HTML files, then go simple. To perform IO access on the file system, Node has an API for that, documented here.

var fs = require('fs');  var fileName = 'path/to/file'; var stream = fs.createWriteStream(fileName);  stream.once('open', function(fd) {   var html = buildHtml();    stream.end(html); }); 

Note: The buildHtml function is exactly the same as in Method 1.


Method 3: Dumping the file directly into stdout

This is the most basic Node.js implementation and requires the invoking application to handle the output itself. To output something in Node (ie. to stdout), the best way is to use console.log(message) where message is any string, or object, etc.

var html = buildHtml();  console.log(html); 

Note: The buildHtml function is exactly the same as in Method 1 (again)

If your script is called html-generator.js (for example), in Linux/Unix based system, simply do

$ node html-generator.js > path/to/file 

Conclusion

Because Node is a modular system, you can even put the buildHtml function inside it's own module and simply write adapters to handle the HTML however you like. Something like

var htmlBuilder = require('path/to/html-builder-module');  var html = htmlBuilder(options); ... 

You have to think "server-side" and not "client-side" when writing JavaScript for Node.js; you are not in a browser and/or limited to a sandbox, other than the V8 engine.

Extra reading, learn about npm. Hope this helps.

like image 93
Yanick Rochon Avatar answered Sep 19 '22 18:09

Yanick Rochon