How to use jQuery with Node.js#

Want to summon the awesome DOM scripting powers of jQuery in Node.js? I have got great news for you - getting jQuery to work in Node.js as easy as 1, 2, 3. Follow me.

First of all, we need to install the jQuery Node module:

$ npm install jquery
...
jquery@1.6.3 ./node_modules/jquery
├── htmlparser@1.7.3
└── jsdom@0.2.10

Notice jsdom and htmlparser? Those are required by jQuery to bring its clientside magic to the serverside. You might come across various articles which uses jsdom and htmlparser for processing DOM in Node.js, you can skip those articles, as long as you want to use jQuery for the purpose.

Also if you see examples containing var request = require('request'), you might wanna skip those articles too because request is an outdated Node module, and hence the examples are outdated too.

Ok, now let's try an example of DOM parsing in Node.js using jQuery. Save the following code in a file named title.js. We call it title.js because it specializes in retrieving the title from a webpage, in this example the webpage is the jQuery homepage.

title.js
var $ = require('jquery');
var http = require('http');

var options = {
  host: 'jquery.com',
  port: 80,
  path: '/'
};

var html = '';
http.get(options, function(res) {
  res.on('data', function(data) {
    // collect the data chunks to the variable named \"html\"
    html += data;
  }).on('end', function() {
    // the whole of webpage data has been collected. parsing time!
    var title = $(html).find('title').text();
    console.log(title);
   });
});

Now run title.js:

$ node title.js
jQuery: The Write Less, Do More, JavaScript Library

w00t! Wan't that easy? That's how you get jQuery working in Node.js. Happy DOM scripting!

References#

  1. jQuery
  2. Node.js - http.get