📜 ⬆️ ⬇️

Run jQuery on the Node.js engine instead of the browser

The jQuery library is a generally recognized means of manipulating several data formats at once (XML, HTML, DOM objects, ordinary objects), and, moreover, it works by means of a convenient (chain) method call with convenient (short) names. Therefore, it is not surprising to try to adapt jQuery not only to one client, but also to server javascript, in particular, to Node.js.

I admit honestly that when jQuery developers overcame problem 7102 , its name (“Register jQuery as a CommonJS async module”) for some time even made me deceive: I thought at first that in Node.js (because Node.js and ommonJS modules have a lot in common) from now on jQuery will work smoothly. But no, it was not there . A close look at the commit and the merge request allows you to realize that jQuery, in essence, has only been able to register as an AMD module and even checks the properties of define.amd and define.amd.jQuery before self-registration.

As a matter of fact, the jQuery architecture is “designed” for use in the browser-based DOM: jQuery code relies on the existence of a window object, which serves as the main closure argument surrounding the entire jQuery code. Before, there were even more such implicit assumptions, and only with the elimination of problem No. 6,690, the jQuery library no longer relied on the existence of global navigator and location objects, instead starting to receive them as properties of the window object. (It is clear that such an assumption did not fit for Node.js, where global objects serve as properties of the global object, and not a window at all; and equally did not apply to many other CommonJS implementations.)
')
Therefore, to run jQuery in Node.js, ready-made implementations of the browser-based DOM are used, such as the jsdom package, on the basis of which, for example, this is the code that is offered as an example:

// Print all of the news items on hackernews var jsdom = require('jsdom'); var fs = require('fs'); var jquery = fs.readFileSync("./jquery-1.6.2.min.js").toString(); jsdom.env({ html: 'http://news.ycombinator.com/', src: [ jquery ], done: function(errors, window) { var $ = window.$; console.log('HN Links'); $('td.title:not(:last) a').each(function() { console.log(' -', $(this).text()); }); } }); 

And jsdom, in turn, is based on the node-jQuery package , which is notable for additional wrappers of syntactic sugar.

There is no other method, no other approach to this problem, but so far there can not be.

Source: https://habr.com/ru/post/134738/


All Articles