Monday, June 4, 2012

Can I use jQuery with node.js?


Is it possible to use jQuery selectors/dom manipulation server-side using node.js ?



Source: Tips4all

8 comments:

  1. Since november 4 2010, simply:

    npm install jquery


    It will fetch the dependencies which are: jsdom and htmlparser

    Npm can be installed here

    Read the thread

    ReplyDelete
  2. Using this library http://github.com/tmpvar/jsdom you now can. Just look at their jquery example in the examples directory.

    ReplyDelete
  3. Yes you can, using a library I created called nodeQuery https://github.com/tblobaum/nodeQuery

    var Express = require('express')
    , dnode = require('dnode')
    , nQuery = require('nodeQuery')
    , express = Express.createServer();

    var app = function ($) {
    $.on('ready', function () {
    // do some stuff to the dom in real-time
    $('body').append('Hello World');
    $('body').append('<input type="text" />');
    $('input').live('click', function () {
    console.log('input clicked');
    // ...
    });
    });
    };

    nQuery
    .use(app);

    express
    .use(nQuery.middleware)
    .use(Express.static(__dirname + '/public'))
    .listen(3000);

    dnode(nQuery.middleware).listen(express);

    ReplyDelete
  4. I believe the answer to this is now yes.
    http://github.com/tmpvar/jsdom/blob/master/example/jquery/run.js

    var navigator = { userAgent: "node-js" };
    var jQuery = require("./node-jquery").jQueryInit(window, navigator);

    ReplyDelete
  5. Jsdom is a great tool. But if you will want to evaluate "whole pages" and doing some funky stuff on them server side i suggest wrapping them into

    vm.runInContext

    So things like require / common js on site will not blow your node process it self.

    more docs: http://nodejs.org/api/vm.html

    Cheers!

    ReplyDelete
  6. No. It's going to be quite a big effort to port a browser environment to node.

    Another approach, that I'm currently investigating for unit testing, is to create "Mock" version of jQuery that provides callbacks whenever a selector is called.

    This way you could unit test your jQuery plugins without actually having a DOM. You'll still have to test in real browsers to see if your code works in the wild, but if you discover browser specific issues, you can easily "mock" those in your unit tests as well.

    I'll push something to github.com/felixge once it's ready to show.

    ReplyDelete
  7. Not that I know of. The DOM is a client side thing (jQuery doesn't parse the HTML, but the DOM).

    Here are some current Node.js projects:

    http://wiki.github.com/ry/node

    And SimonW's djangode is pretty damn cool...

    ReplyDelete
  8. An alternative is to use Underscore.js. It should provide what you might have wanted server-side from JQuery.

    ReplyDelete