Programing

Node.js와 함께 jQuery를 사용할 수 있습니까?

crosscheck 2020. 10. 4. 10:29
반응형

Node.js와 함께 jQuery를 사용할 수 있습니까?


Node.js를 사용하여 서버 측에서 jQuery 선택기 / DOM 조작을 사용할 수 있습니까?


업데이트 (27-Jun-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);

참고 : 원래 대답은 jsdom을 설치해야한다고 언급하지 않습니다.npm install jsdom

업데이트 (2013 년 말) : 공식 jQuery 팀이 마침내 jquerynpm 에서 패키지 관리를 인수했습니다 .

npm install jquery

그때:

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


예, 제가 만든 nodeQuery 라는 라이브러리를 사용하여 할 수 있습니다.

var Express = require('express')
    , dnode = require('dnode')
    , nQuery = require('nodeQuery')
    , express = Express.createServer();

var app = function ($) {
    $.on('ready', function () {
        // do some stuff to the dom in real-time
        $('body').append('Hello World');
        $('body').append('<input type="text" />');
        $('input').live('click', function () {
            console.log('input clicked');
            // ...
        });
    });
};

nQuery
    .use(app);

express
    .use(nQuery.middleware)
    .use(Express.static(__dirname + '/public'))
    .listen(3000);

dnode(nQuery.middleware).listen(express);

글을 쓰는 시점에 유지되는 Cheerio도 있습니다.

서버를 위해 특별히 설계된 핵심 jQuery의 빠르고 유연하며 간결한 구현입니다.


jsdom사용 하면 이제 할 수 있습니다. examples 디렉토리에서 jquery 예제를 살펴보십시오.


Cheerio를 사용하는 간단한 크롤러

이것은 Node.js에서 간단한 크롤러를 만드는 공식입니다. 서버 측에서 DOM 조작을 원하는 주된 이유이며 아마도 여기에 온 이유 일 것입니다.

먼저 request파싱 ​​할 페이지를 다운로드하는 데 사용 합니다. 다운로드가 완료되면 cheeriojQuery를 사용하는 것처럼 처리하고 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 설치 요청 cheerio

그리고 실행하십시오 (위의 스크립트가 file에 있다고 가정 crawler.js) :

node crawler.js


부호화

일부 페이지에는 특정 인코딩으로 된 비 영어 콘텐츠가 포함되어 있으며이를로 디코딩해야합니다 UTF-8. 예를 들어, 브라질 포르투갈어 (또는 라틴어 기원의 다른 언어)로 된 페이지는 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 cheerio

그리고 마지막으로 :

node crawler.js


다음 링크

다음 단계는 링크를 따르는 것입니다. SO에 각 상위 질문의 모든 포스터를 나열하고 싶다고 가정 해 보겠습니다. 먼저 모든 상위 질문 (위의 예)을 나열한 다음 각 링크를 입력하고 각 질문의 페이지를 구문 분석하여 관련 사용자 목록을 가져와야합니다.

링크를 따라 가기 시작하면 콜백 지옥 이 시작될 수 있습니다. 이를 방지하려면 어떤 종류의 약속, 선물 등을 사용해야합니다. 나는 항상 내 도구 벨트에서 비동기유지 합니다. 따라서 다음은 비동기를 사용하는 크롤러의 전체 예입니다.

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 설치 요청 비동기 cheerio

테스트 실행 :

node 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

이것이 바로 크롤러를 만들기 위해 알아야 할 기본 사항입니다. :-)


사용 된 라이브러리


2016 년에는 일이 훨씬 쉬워졌습니다. 콘솔을 사용하여 jquery를 node.js에 설치합니다.

npm install jquery

bind it to the variable $ (for example - i am used to it) in your node.js code:

var $ = require("jquery");

do stuff:

$.ajax({
    url: 'gimme_json.php',
    dataType: 'json',
    method: 'GET',
    data: { "now" : true }
});

also works for gulp as it is based on node.js.


I believe the answer to this is now yes.
https://github.com/tmpvar/jsdom

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

npm install jquery --save #note ALL LOWERCASE

npm install jsdom --save

const jsdom = require("jsdom");
const dom = new jsdom.JSDOM(`<!DOCTYPE html>`);
var $ = require("jquery")(dom.window);


$.getJSON('https://api.github.com/users/nhambayi',function(data) {
  console.log(data);
});

jQuery module can be installed using:

npm install jquery

Example:

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

References of jQuery in Node.js** :


You have to get the window using the new JSDOM API.

const jsdom = require("jsdom");
const { window } = new jsdom.JSDOM(`...`);
var $ = require("jquery")(window);

WARNING

This solution, as mentioned by Golo Roden is not correct. It is just a quick fix to help people to have their actual jQuery code running using a Node app structure, but it's not Node philosophy because the jQuery is still running on the client side instead of on the server side. I'm sorry for giving a wrong answer.


You can also render Jade with node and put your jQuery code inside. Here is the code of the jade file:

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

My working code is:

npm install jquery

and then:

global.jQuery   = require('jquery');
global.$        = global.jQuery;

or if the window is present, then:

typeof window !== "undefined" ? window : this;
window.jQuery   = require('jquery');
window.$        = window.jQuery;

First of all install it

npm install jquery -S

After installing it, you can use it as below

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

You can check out the full tutorial here: https://medium.com/fbdevclagos/how-to-use-jquery-on-node-df731bd6abc7


The module jsdom is a great tool. But if you want to evaluate entire pages and do some funky stuff on them server side I suggest running them in their own context:

vm.runInContext

So things like require / CommonJS on site will not blow your Node process itself.

You can find documentation here. Cheers!


As of jsdom v10, .env() function is deprecated. I did it like below after trying a lot of things to require jquery:

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

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

Hope this helps you or anyone who has been facing these types of issues.


No. It's going to be quite a big effort to port a browser environment to node.

Another approach, that I'm currently investigating for unit testing, is to create "Mock" version of jQuery that provides callbacks whenever a selector is called.

This way you could unit test your jQuery plugins without actually having a DOM. You'll still have to test in real browsers to see if your code works in the wild, but if you discover browser specific issues, you can easily "mock" those in your unit tests as well.

I'll push something to github.com/felixge once it's ready to show.


You can use Electron, it allows hybrid browserjs and nodejs.

Before, I tried to use canvas2d in nodejs, but finally I gave up. It's not supported by nodejs default, and too hard to install it (many many ... dependeces). Until I use Electron, I can easily use all my previous browserjs code, even WebGL, and pass the result value(eg. result base64 image data) to nodejs code.


Not that I know of. The DOM is a client side thing (jQuery doesn't parse the HTML, but the DOM).

Here are some current Node.js projects:

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

And SimonW's djangode is pretty damn cool...


An alternative is to use Underscore.js. It should provide what you might have wanted server-side from JQuery.

참고URL : https://stackoverflow.com/questions/1801160/can-i-use-jquery-with-node-js

반응형