是否有可能在服务器端使用Node.js使用jQuery选择器/DOM操作?


当前回答

jQuery模块可以通过以下方式安装:

npm install jquery

例子:

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);
 });
});

jQuery在Node.js中的引用**:

http://quaintous.com/2015/07/31/jqery-node-mystery/ http://www.hacksparrow.com/jquery-with-node-js.html

其他回答

我相信这个问题的答案是肯定的。 https://github.com/tmpvar/jsdom

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

在写这篇文章的时候,也有保持的Cheerio。

快速,灵活,精益的实现核心jQuery设计 特别是针对服务器。

这些解决方案在我的电子应用程序中没有一个对我有帮助。

我的解决方案(变通方案):

npm install jquery

在index.js文件中:

var jQuery = $ = require('jquery');

在你的.js文件中,以这样的方式编写jQuery函数:

jQuery(document).ready(function() {

你可以使用Electron,它允许混合browserjs和nodejs。

之前,我尝试在nodejs中使用canvas2d,但最后我放弃了。它不被nodejs默认支持,并且很难安装它(很多很多…dependeces)。 直到我使用电子,我可以很容易地使用所有我以前的browserjs代码,甚至WebGL,并传递结果值(例如。结果base64图像数据)到nodejs代码。

更新(6月27日-18日):看起来jsdom有一个重大更新,导致原来的答案不再工作。我找到了这个解释如何使用jsdom的答案。我复制了下面的相关代码。

var jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { window } = new JSDOM();
const { document } = (new JSDOM('')).window;
global.document = document;

var $ = jQuery = require('jquery')(window);

注意:原来的答案没有提到你也需要使用npm install jsdom来安装jsdom

更新(2013年底):官方jQuery团队终于接管了npm上jQuery包的管理:

npm install jquery

然后:

require("jsdom").env("", function (err, window) {
    if (err) {
        console.error(err);
        return;
    }
    var $ = require("jquery")(window);
});