[javascript] 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?

This question is related to javascript html node.js

The answer is


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 :

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.


You can use jade + express:

app.get('/', function (req, res) { res.render('index', { title : 'Home' } ) });

above you see 'index' and an object {title : 'Home'}, 'index' is your html and the object is your data that will be rendered in your html.


You can use jsdom

const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { document } = (new JSDOM(`...`)).window;

or, take a look at cheerio, it may more suitable in your case.


Although @yanick-rochon answer is correct, the simplest way to achieve your goal (if it's to serve a dynamically generated html) is:

var http = require('http');
http.createServer(function (req, res) {
  res.write('<html><head></head><body>');
  res.write('<p>Write your HTML content here</p>');
  res.end('</body></html>');
}).listen(1337);

This way when you browse at http://localhost:1337 you'll get your html page.


If you want to create static files, you can use Node.js File System Library to do that. But if you are looking for a way to create dynamic files as a result of your database or similar queries then you will need a template engine like SWIG. Besides these options you can always create HTML files as you would normally do and serve them over Node.js. To do that, you can read data from HTML files with Node.js File System and write it into response. A simple example would be:

var http = require('http');
var fs   = require('fs');

http.createServer(function (req, res) {
  fs.readFile(req.params.filepath, function (err, content) {
    if(!err) {
      res.end(content);
    } else {
      res.end('404');
    }
  }
}).listen(3000);

But I suggest you to look into some frameworks like Express for more useful solutions.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`