1

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()));
});
1
  • Did my answer below help you? Any comments? Commented Nov 24, 2016 at 21:11

1 Answer 1

1

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:

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry I haven't had time to try this out yet. I will report back soon-ish. This looks promising though. I was confused about the readfile a bit because when I just console.logged the html, it gave me a huge insensible "stream array", but the .toString might be the key!
Yeah your answer works just as expected! If you have time, could you provide an explanation as to why I can call toString() on a result of filestream(?) and how it works?

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.