jQuery with Node.js
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 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.
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
--------------- The Title ------------------
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!
Awesome mini-guide. Was looking for some more up-to-date information about use of jquery with Node.js – instead of calling jsdom directly.
Thanks!
Just a quick comment, currently is not possible to install jquery using “npm install jquery” there is a problem building contextify (https://npmjs.org/package/jquery).
As a workaround you can try jsdom https://github.com/tmpvar/jsdom.
Hope this helps somebody else time!
Cheers!
Nicolás
Forgot something! I meant, it’s not possible to install jquery using npm install jquery in Windows!
Found out that jsdom depends on contextify as well so it’s not a good workaround….
I’m using cheerio + request libs for parsing HTML and it works perfectly fine.
This library will not work for window environment. jquery , nodequery or even jsdom…