0

for example i want use jquery function extend

var object = $.extend({}, object1, object2); 

But :

 var $ = require('jquery');  

console : $

function ( w ) {
                if ( !w.document ) {
                    throw new Error( "jQuery requires a window with a doc…  

$.extend undefined

3
  • 1
    What's your version of jQuery? And I quote from npmjs.org/package/jquery: "To use jQuery in Node, browser extensions, and other non-browser environments, use only 2.x releases. 1.x does not support these environments." Commented Sep 2, 2014 at 11:29
  • Also please write out the full error message clearly, this will help get us to an answer Commented Sep 2, 2014 at 11:30
  • For reference sake the full error message was: "jQuery requires a window with a document" Commented Sep 2, 2014 at 16:39

2 Answers 2

3

You can get this to work but you'll need another module called jsdom because jQuery needs a DOM window to operate, it's not designed for Node.js. Install it with:

npm install jsdom --save

Please note: I'm using the latest jQuery 2.1.1 and jsdom 1.0.0-pre.6 both installed via npm

And then in your Node.js file e.g. app.js:

var jsdom = require('jsdom'),
    window = jsdom.jsdom().parentWindow,
    $ = require('jquery')(window);

var object = $.extend({},{'foo':'bar'},{'cat':'dog'});
console.log(object);

Then in Node.js you run it:

node app.js

And see the output:

{ foo: 'bar', cat: 'dog' }

Perhaps the better option is to use something like cheerio which is a "fast, flexible, and lean implementation of core jQuery designed specifically for the server". You can install this with npm install cheerio.

Sign up to request clarification or add additional context in comments.

Comments

2

jquery is only for client side. For server side (node.js0, it used for unitTest scripting with browserify, ... because node.js has no window, document and DOM layer. I recommand you to use underscore.js :

npm install underscore

Underscore.js has a extend method works like jquery.extend. :

var _ = require('underscore');
var obj = _.extend({}, object1, object2);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.