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


当前回答

警告

这个解决方案,正如Golo Roden提到的是不正确的。它只是一个快速修复,帮助人们使用Node应用程序结构运行实际的jQuery代码,但它不是Node哲学,因为jQuery仍然运行在客户端,而不是在服务器端。我很抱歉给了一个错误的答案。


您还可以使用节点渲染Jade,并将jQuery代码放在其中。下面是jade文件的代码:

!!! 5
html(lang="en")
  head
    title Holamundo!
    script(type='text/javascript', src='http://code.jquery.com/jquery-1.9.1.js')
  body
    h1#headTitle Hello, World
    p#content This is an example of Jade.
    script
      $('#headTitle').click(function() {
        $(this).hide();
      });
      $('#content').click(function() {
        $(this).hide();
      });

其他回答

据我所知没有。DOM是一个客户端的东西(jQuery不解析HTML,但解析DOM)。

下面是一些当前的Node.js项目:

https://github.com/ry/node/wiki (https://github.com/nodejs/node)

SimonW的djangode非常酷…

一个使用Cheerio的简单爬虫程序

这是我在Node.js中制作一个简单爬虫程序的公式。这是想要在服务器端进行DOM操作的主要原因,也可能是这里的原因。

首先,使用request下载要解析的页面。下载完成后,将其处理为cheerio,并像使用jQuery一样开始DOM操作。

工作的例子:

var
    request = require('request'),
    cheerio = require('cheerio');

function parse(url) {
    request(url, function (error, response, body) {
        var
            $ = cheerio.load(body);

        $('.question-summary .question-hyperlink').each(function () {
            console.info($(this).text());
        });
    })
}

parse('http://stackoverflow.com/');

这个例子将打印到控制台的所有顶级问题显示在SO主页。这就是为什么我喜欢Node.js和它的社区。没有比这更容易的了:-)

安装的依赖关系:

NPM安装请求

然后运行(假设上面的脚本在爬虫.js文件中):

节点crawler.js


编码

有些页面会有某种编码的非英语内容,您需要将其解码为UTF-8。例如,巴西葡萄牙语(或任何其他起源于拉丁语的语言)的页面可能会被编码为ISO-8859-1(也就是ISO-8859-1)。“latin1”中的一个)。当需要解码时,我告诉request不要以任何方式解释内容,而是使用iconv-lite来完成工作。

工作的例子:

var
    request = require('request'),
    iconv = require('iconv-lite'),
    cheerio = require('cheerio');

var
    PAGE_ENCODING = 'utf-8'; // change to match page encoding

function parse(url) {
    request({
        url: url,
        encoding: null  // do not interpret content yet
    }, function (error, response, body) {
        var
            $ = cheerio.load(iconv.decode(body, PAGE_ENCODING));

        $('.question-summary .question-hyperlink').each(function () {
            console.info($(this).text());
        });
    })
}

parse('http://stackoverflow.com/');

运行之前,安装依赖项:

NPM安装请求iconv-lite

最后:

节点crawler.js


下面的链接

下一步是跟踪链接。假设你想在SO上列出每个顶级问题的所有海报。您必须首先列出所有主要问题(如上例),然后进入每个链接,解析每个问题的页面以获得涉及的用户列表。

当您开始跟踪链接时,回调地狱就开始了。为了避免这种情况,你应该使用一些承诺,未来或其他东西。我总是在我的工具带中保持异步。下面是一个使用async的爬虫的完整示例:

var
    url = require('url'),
    request = require('request'),
    async = require('async'),
    cheerio = require('cheerio');

var
    baseUrl = 'http://stackoverflow.com/';

// Gets a page and returns a callback with a $ object
function getPage(url, parseFn) {
    request({
        url: url
    }, function (error, response, body) {
        parseFn(cheerio.load(body))
    });
}

getPage(baseUrl, function ($) {
    var
        questions;

    // Get list of questions
    questions = $('.question-summary .question-hyperlink').map(function () {
        return {
            title: $(this).text(),
            url: url.resolve(baseUrl, $(this).attr('href'))
        };
    }).get().slice(0, 5); // limit to the top 5 questions

    // For each question
    async.map(questions, function (question, questionDone) {

        getPage(question.url, function ($$) {

            // Get list of users
            question.users = $$('.post-signature .user-details a').map(function () {
                return $$(this).text();
            }).get();

            questionDone(null, question);
        });

    }, function (err, questionsWithPosters) {

        // This function is called by async when all questions have been parsed

        questionsWithPosters.forEach(function (question) {

            // Prints each question along with its user list
            console.info(question.title);
            question.users.forEach(function (user) {
                console.info('\t%s', user);
            });
        });
    });
});

跑步前:

NPM安装请求异步

运行一个测试:

节点crawler.js

样例输出:

Is it possible to pause a Docker image build?
    conradk
    Thomasleveil
PHP Image Crop Issue
    Elyor
    Houston Molinar
Add two object in rails
    user1670773
    Makoto
    max
Asymmetric encryption discrepancy - Android vs Java
    Cookie Monster
    Wand Maker
Objective-C: Adding 10 seconds to timer in SpriteKit
    Christian K Rider

这是你应该知道的基本开始制作你自己的爬虫:-)


库的使用

请求 iconv-lite 恭喜恭喜 异步

首先,安装它

npm install jquery -S

安装后,您可以如下所示使用它

import $ from 'jquery';
window.jQuery = window.$ = $;
$(selector).hide();

你可以查看我写的完整教程:https://medium.com/fbdevclagos/how-to-use-jquery-on-node-df731bd6abc7

另一种选择是使用Underscore.js。它应该提供您可能需要的JQuery服务器端功能。

不。将浏览器环境移植到节点需要付出很大的努力。

我目前正在研究的另一种用于单元测试的方法是创建jQuery的“Mock”版本,在调用选择器时提供回调。

这样你就可以在没有DOM的情况下对jQuery插件进行单元测试。您仍然需要在真正的浏览器中进行测试,以查看代码是否可以正常工作,但如果您发现了特定于浏览器的问题,您也可以在单元测试中轻松地“模拟”这些问题。

一旦它准备好了,我会把一些东西推送到github.com/felixge。