Piwwoli Piwwoli - 1 year ago 80
HTML Question

How to read a HTML file for jQuery, using Node.js

I am creating a desktop application using web-technologies and "client-side" node.js. By using NWJS, I can load node-modules "client-side".

I would like to use something like the node's

to load a client-side .html-file and then turn that into a jQuery-object that I can, for example, append somewhere.

I know jQuery has it's own
-method, but I would like to use node.js to load the file.

Edit: It is working now based on the answer by rsp

Working code:

fs.readFile('./views/main.html', function (err, html)
if (err)
throw err;


rsp rsp
Answer Source

If you can use fs.readFile and jQuery in the same context then you can read the file and parse it with jQuery with something like this:

fs.readFile('/path/to/file', function (err, html) {
  if (err) {
    // handle error
  } else {
    var $html = $(html.toString());
    // now $html is a jQuery object

It's pretty much the same as if you do $('<p>abc</p>') with jQuery. You can pass an HTML string to the jQuery function and it returns a jQuery objects. Here the only difference is that the string came from the file.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download