Rectangle 27 487

Update: (late 2013) The official jQuery team finally took over the management of the jquery package on npm:

npm install jquery
require("jsdom").env("", function(err, window) {
    if (err) {
        console.error(err);
        return;
    }

    var $ = require("jquery")(window);
});

Is it possible to use jQuery ajax from node.js with that npm module?

Doesn't install on Windows (without significant work), in which case I would recommend the Cheerio module: matthewmueller.github.com/cheerio

+1 for showing where to get npm :) most people have a bad habit of just mentioning stuff as if it should be a given (common sense)

require("...").env is not a function

javascript - Can I use jQuery with Node.js? - Stack Overflow

javascript jquery node.js
Rectangle 27 487

Update: (late 2013) The official jQuery team finally took over the management of the jquery package on npm:

npm install jquery
require("jsdom").env("", function(err, window) {
    if (err) {
        console.error(err);
        return;
    }

    var $ = require("jquery")(window);
});

Is it possible to use jQuery ajax from node.js with that npm module?

Doesn't install on Windows (without significant work), in which case I would recommend the Cheerio module: matthewmueller.github.com/cheerio

+1 for showing where to get npm :) most people have a bad habit of just mentioning stuff as if it should be a given (common sense)

require("...").env is not a function

javascript - Can I use jQuery with Node.js? - Stack Overflow

javascript jquery node.js
Rectangle 27 487

Update: (late 2013) The official jQuery team finally took over the management of the jquery package on npm:

npm install jquery
require("jsdom").env("", function(err, window) {
    if (err) {
        console.error(err);
        return;
    }

    var $ = require("jquery")(window);
});

Is it possible to use jQuery ajax from node.js with that npm module?

Doesn't install on Windows (without significant work), in which case I would recommend the Cheerio module: matthewmueller.github.com/cheerio

+1 for showing where to get npm :) most people have a bad habit of just mentioning stuff as if it should be a given (common sense)

require("...").env is not a function

javascript - Can I use jQuery with Node.js? - Stack Overflow

javascript jquery node.js
Rectangle 27 49

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

Note that nodeQuery is actually changing the page of the user in real time, so it's even cooler than one might expect.

I was searching something like this when I stumbled here... I have just looked at nQuery and jquery node packages and nQuery was updated a year ago where jquery was yesterday... Is nQuery no longer developed? and does jquery affect client side as nQuery does? Has anybody tried them both maybe?

@Logan nQuery is basically just jquery. the difference is the code is run on the server and, rather than delivering the jquery code to the browser, it runs the code on the server and remotely executes dom manipulation to connected browsers. Also note that nQuery was an experimental project, and while I will accept pull requests to fix bugs, it was never created for any specific purpose or project so it has not had many commits

, express = Express.createServer();
TypeError: Express.createServer is not a function

javascript - Can I use jQuery with Node.js? - Stack Overflow

javascript jquery node.js
Rectangle 27 45

At the time of writing there also is the maintained Cheerio.

Fast, flexible, and lean implementation of core jQuery designed specifically for the server.

+1 for Cheerio. jsdom, on the other hand, is really painful to get running on Windows.

does not support a lot of selectors like :gt(1)

javascript - Can I use jQuery with Node.js? - Stack Overflow

javascript jquery node.js
Rectangle 27 35

one down side of jsdom's jQueryify() is that it runs all the page's scripts.

javascript - Can I use jQuery with Node.js? - Stack Overflow

javascript jquery node.js
Rectangle 27 49

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

Note that nodeQuery is actually changing the page of the user in real time, so it's even cooler than one might expect.

I was searching something like this when I stumbled here... I have just looked at nQuery and jquery node packages and nQuery was updated a year ago where jquery was yesterday... Is nQuery no longer developed? and does jquery affect client side as nQuery does? Has anybody tried them both maybe?

@Logan nQuery is basically just jquery. the difference is the code is run on the server and, rather than delivering the jquery code to the browser, it runs the code on the server and remotely executes dom manipulation to connected browsers. Also note that nQuery was an experimental project, and while I will accept pull requests to fix bugs, it was never created for any specific purpose or project so it has not had many commits

, express = Express.createServer();
TypeError: Express.createServer is not a function

javascript - Can I use jQuery with Node.js? - Stack Overflow

javascript jquery node.js
Rectangle 27 49

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

Note that nodeQuery is actually changing the page of the user in real time, so it's even cooler than one might expect.

I was searching something like this when I stumbled here... I have just looked at nQuery and jquery node packages and nQuery was updated a year ago where jquery was yesterday... Is nQuery no longer developed? and does jquery affect client side as nQuery does? Has anybody tried them both maybe?

@Logan nQuery is basically just jquery. the difference is the code is run on the server and, rather than delivering the jquery code to the browser, it runs the code on the server and remotely executes dom manipulation to connected browsers. Also note that nQuery was an experimental project, and while I will accept pull requests to fix bugs, it was never created for any specific purpose or project so it has not had many commits

, express = Express.createServer();
TypeError: Express.createServer is not a function

javascript - Can I use jQuery with Node.js? - Stack Overflow

javascript jquery node.js
Rectangle 27 7

I am also sharing code between a browser and nodejs and also use JQuery for Ajax calls. JQuery requires a window which I use from domino.

if (typeof module !== 'undefined' && module.exports)
{
  if (typeof global !== 'undefined' && typeof global.process !== 'undefined' &&
    Object.prototype.toString.call(global.process) === '[object process]') {
    var domino = require('domino');
    var window = domino.createWindow('<html></html>');

    var document = window.document;
    var $ = require('jquery')(window);
    var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
    $.support.cors = true; // cross domain, Cross-origin resource sharing
    $.ajaxSettings.xhr = function() {
      return new XMLHttpRequest();
    };
  }
}

Why are you exporting "huepi" when its not defined anywhere?

Good point :). I copied it from my project that uses this, It is called huepi: github.com/arndbrugman/huepi. I'll remove it from the code above. Thx for noticing!

jQuery.ajax() in node.js? - Stack Overflow

jquery node.js
Rectangle 27 7

I am also sharing code between a browser and nodejs and also use JQuery for Ajax calls. JQuery requires a window which I use from domino.

if (typeof module !== 'undefined' && module.exports)
{
  if (typeof global !== 'undefined' && typeof global.process !== 'undefined' &&
    Object.prototype.toString.call(global.process) === '[object process]') {
    var domino = require('domino');
    var window = domino.createWindow('<html></html>');

    var document = window.document;
    var $ = require('jquery')(window);
    var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
    $.support.cors = true; // cross domain, Cross-origin resource sharing
    $.ajaxSettings.xhr = function() {
      return new XMLHttpRequest();
    };
  }
}

Why are you exporting "huepi" when its not defined anywhere?

Good point :). I copied it from my project that uses this, It is called huepi: github.com/arndbrugman/huepi. I'll remove it from the code above. Thx for noticing!

jQuery.ajax() in node.js? - Stack Overflow

jquery node.js
Rectangle 27 45

At the time of writing there also is the maintained Cheerio.

Fast, flexible, and lean implementation of core jQuery designed specifically for the server.

+1 for Cheerio. jsdom, on the other hand, is really painful to get running on Windows.

does not support a lot of selectors like :gt(1)

javascript - Can I use jQuery with Node.js? - Stack Overflow

javascript jquery node.js
Rectangle 27 45

At the time of writing there also is the maintained Cheerio.

Fast, flexible, and lean implementation of core jQuery designed specifically for the server.

+1 for Cheerio. jsdom, on the other hand, is really painful to get running on Windows.

does not support a lot of selectors like :gt(1)

javascript - Can I use jQuery with Node.js? - Stack Overflow

javascript jquery node.js
Rectangle 27 23

This is my formula to make a simple crawler in Node.js. It is the main reason for wanting to do DOM manipulation on the server side and probably it's the reason why you got here.

First, use request to download the page to be parsed. When the download is complete, handle it to cheerio and begin DOM manipulation just like using jQuery.

This example will print to the console all top questions showing on SO home page. This is why I love Node.js and its community. It couldn't get easier than that :-)

And run (assuming the script above is in file crawler.js):

Some pages will have non-english content in a certain encoding and you will need to decode it to UTF-8. For instance, a page in brazilian portuguese (or any other language of latin origin) will likely be encoded in ISO-8859-1 (a.k.a. "latin1"). When decoding is needed, I tell request not to interpret the content in any way and instead use iconv-lite to do the job.

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/');

The next step would be to follow links. Say you want to list all posters from each top question on SO. You have to first list all top questions (example above) and then enter each link, parsing each question's page to get the list of involved users.

When you start following links, a callback hell can begin. To avoid that, you should use some kind of promises, futures or whatever. I always keep async in my toolbelt. So, here is a full example of a crawler using 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);
            });
        });
    });
});

Run a test:

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

And that's the basic you should know to start making your own crawlers :-)

javascript - Can I use jQuery with Node.js? - Stack Overflow

javascript jquery node.js
Rectangle 27 35

one down side of jsdom's jQueryify() is that it runs all the page's scripts.

javascript - Can I use jQuery with Node.js? - Stack Overflow

javascript jquery node.js
Rectangle 27 35

one down side of jsdom's jQueryify() is that it runs all the page's scripts.

javascript - Can I use jQuery with Node.js? - Stack Overflow

javascript jquery node.js
Rectangle 27 17

in 2016 things are way easier. install jquery to node.js with your console:

npm install jquery

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

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

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

What version of node are you using? On Mac, Node 6.10.2, jquery 2.2.4, var $ = require("jquery"); $.ajax // undefined (Downvoted for the moment).

@AJP and you are sure you did npm install jquery first?

> console.log(require("jquery").toString());
function ( w ) {   if ( !w.document ) {     throw new Error( "jQuery requires a window with a document" );   }   return factory( w ); }

any update on this? having the same issues.

javascript - Can I use jQuery with Node.js? - Stack Overflow

javascript jquery node.js
Rectangle 27 16

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

I'm sorry to report that it is going to take more work to get jQuery running on jsdom. Sizzle however does work! I really want to keep jsdom as light as possible, so adding in full browser emulation like env.js is not really a priority at this time.

never mind, i found the modified copy that's bundled with jsdom.

javascript - Can I use jQuery with Node.js? - Stack Overflow

javascript jquery node.js
Rectangle 27 23

This is my formula to make a simple crawler in Node.js. It is the main reason for wanting to do DOM manipulation on the server side and probably it's the reason why you got here.

First, use request to download the page to be parsed. When the download is complete, handle it to cheerio and begin DOM manipulation just like using jQuery.

This example will print to the console all top questions showing on SO home page. This is why I love Node.js and its community. It couldn't get easier than that :-)

And run (assuming the script above is in file crawler.js):

Some pages will have non-english content in a certain encoding and you will need to decode it to UTF-8. For instance, a page in brazilian portuguese (or any other language of latin origin) will likely be encoded in ISO-8859-1 (a.k.a. "latin1"). When decoding is needed, I tell request not to interpret the content in any way and instead use iconv-lite to do the job.

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/');

The next step would be to follow links. Say you want to list all posters from each top question on SO. You have to first list all top questions (example above) and then enter each link, parsing each question's page to get the list of involved users.

When you start following links, a callback hell can begin. To avoid that, you should use some kind of promises, futures or whatever. I always keep async in my toolbelt. So, here is a full example of a crawler using 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);
            });
        });
    });
});

Run a test:

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

And that's the basic you should know to start making your own crawlers :-)

javascript - Can I use jQuery with Node.js? - Stack Overflow

javascript jquery node.js
Rectangle 27 22

This is my formula to make a simple crawler in Node.js. It is the main reason for wanting to do DOM manipulation on the server side and probably it's the reason why you got here.

First, use request to download the page to be parsed. When the download is complete, handle it to cheerio and begin DOM manipulation just like using jQuery.

This example will print to the console all top questions showing on SO home page. This is why I love Node.js and its community. It couldn't get easier than that :-)

And run (assuming the script above is in file crawler.js):

Some pages will have non-english content in a certain encoding and you will need to decode it to UTF-8. For instance, a page in brazilian portuguese (or any other language of latin origin) will likely be encoded in ISO-8859-1 (a.k.a. "latin1"). When decoding is needed, I tell request not to interpret the content in any way and instead use iconv-lite to do the job.

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/');

The next step would be to follow links. Say you want to list all posters from each top question on SO. You have to first list all top questions (example above) and then enter each link, parsing each question's page to get the list of involved users.

When you start following links, a callback hell can begin. To avoid that, you should use some kind of promises, futures or whatever. I always keep async in my toolbelt. So, here is a full example of a crawler using 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);
            });
        });
    });
});

Run a test:

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

And that's the basic you should know to start making your own crawlers :-)

javascript - Can I use jQuery with Node.js? - Stack Overflow

javascript jquery node.js
Rectangle 27 17

in 2016 things are way easier. install jquery to node.js with your console:

npm install jquery

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

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

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

What version of node are you using? On Mac, Node 6.10.2, jquery 2.2.4, var $ = require("jquery"); $.ajax // undefined (Downvoted for the moment).

@AJP and you are sure you did npm install jquery first?

> console.log(require("jquery").toString());
function ( w ) {   if ( !w.document ) {     throw new Error( "jQuery requires a window with a document" );   }   return factory( w ); }

any update on this? having the same issues.

javascript - Can I use jQuery with Node.js? - Stack Overflow

javascript jquery node.js