从Node初始化jquery

我正在创build一个新项目,使用以下内容:

$mkdir X $cd X $npm install jquery 

然后创build一个新的app.js文件:

 var http = require('http'); var $ = require('jquery'); console.log("http="+ http); console.log("$="+ $); console.log("$.getJSON="+ $.getJSON); 

输出是:

 http=[object Object] $=function ( w ) {...} $.getJSON=undefined 

为什么$ .getJSON未定义? 使用最新的io.js v2.4.0。

您正试图从Node.js中创build一个XHR 。 这是不行的,因为Node.js只是一个JavaScript运行时,并不像浏览器一样。

如果你想从HTTP协议的某个地方获取某些东西,你可以使用类似request东西。 例如(来自官方文档):

 var request = require('request'); request('http://www.google.com', function (error, response, body) { if (!error && response.statusCode == 200) { console.log(body) // Show the HTML for the Google homepage. } }) 

你可以看看这个答案 (同样来自我),了解更多关于使用jQuery和Node.js结合使用的信息。

更新[d再次!]:

所以你想知道jQuery节点模块如何区分浏览器和节点环境? 当你require在CommonJS或提供modulemodule.exports类似环境中使用jQuery时,你得到的是一个工厂,而不是实际的jQuery对象。 正如你在下面看到的,这个工厂可以用来创build一个jQuery对象,即使用jsdom :

 let jsdom = require("jsdom"); let $ = null; jsdom.env( "http://quaintous.com/2015/07/31/jquery-node-mystery/", function (err, window) { $ = require('jQuery')(window); } ); 

以下是jQuery如何区分浏览器和io.js(或Node.js):

 (function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper `window` // is present, execute the factory and get jQuery. // For environments that do not have a `window` with a `document` // (such as Node.js), expose a factory as module.exports. // This accentuates the need for the creation of a real `window`. // eg var jQuery = require("jquery")(window); // See ticket #14549 for more info. module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // implementation return jQuery; })); 

我会使用jQuery的npm包是为了定制构build,而不是用于require

更新

我感觉这个主题碰巧让一些开发人员很忙,所以我结合了我自己的答案,并写了一篇关于整个jQuery / Node组合的文章!

如果你想同步加载jquery,你可以使用类似下面的东西

 var jsdom = require('jsdom'); var jQuery = require('jquery')(jsdom.jsdom('<p><a>jsdom!</a></p>').defaultView);