node.js - Initializing jquery from Node -
i creating new project using following:
$mkdir x $cd x $npm install jquery
then create new app.js file:
var http = require('http'); var $ = require('jquery'); console.log("http="+ http); console.log("$="+ $); console.log("$.getjson="+ $.getjson);
output is:
http=[object object] $=function ( w ) {...} $.getjson=undefined
why $.getjson undefined ? using latest io.js v2.4.0.
you trying create xhr
within node.js. not going work since node.js javascript runtime , not same browser.
if want fetch somewhere on http protocol, can use request
. example (from official docs):
var request = require('request'); request('http://www.google.com', function (error, response, body) { if (!error && response.statuscode == 200) { console.log(body) // show html google homepage. } })
you can take @ this answer (also me) more information on using jquery in combination node.js.
update[d again!]:
so wanted know how jquery node module differentiates between browser , node environment? when require
jquery inside commonjs or similar environment provide module
, module.exports
, factory , not actual jquery object. can see below, factory can used create jquery object, i.e. using jsdom:
let jsdom = require("jsdom"); let $ = null; jsdom.env( "http://quaintous.com/2015/07/31/jquery-node-mystery/", function (err, window) { $ = require('jquery')(window); } );
here how jquery differentiates between browser , io.js (or node.js):
(function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // commonjs , commonjs-like environments proper `window` // present, execute factory , jquery. // environments not have `window` `document` // (such node.js), expose factory module.exports. // accentuates need creation of real `window`. // e.g. var jquery = require("jquery")(window); // see ticket #14549 more info. module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new error( "jquery requires window document" ); } return factory( w ); }; } else { factory( global ); } // pass if window not defined yet }(typeof window !== "undefined" ? window : this, function( window, noglobal ) { // implementation return jquery; }));
i use jquery's npm package meant custom builds rather used require
!
update:
i had feeling subject happens keep devs busy, combined couple of own answers , wrote an article whole jquery/node combination!
Comments
Post a Comment