Search code examples
javascriptjqueryhtmlnode.jsnwjs

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 fs.readFile 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 .load()-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; 
    }     

    $('#toolview').empty().append($(html.toString()));
});

Solution

  • 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.

    What you get from readFile by default is not a String but a Buffer. It was added before there was TypedArray in ES6 to be able to process files and streams of binary data with good performance.

    To convert the Buffer to String you can use the toString method that optionally takes the encoding (UTF-8 by default), start and end of the buffer to convert (the entire buffer by default).

    For more info see: