TEST");console.log($("body").html( ));Run node app.js"/> TEST");console.log($("body").html( ));Run node app.js">

Home  >  Article  >  Web Front-end  >  How to use jQuery in Node.js

How to use jQuery in Node.js

怪我咯
怪我咯Original
2017-03-30 09:33:061774browse

First, we have to install jquery, npm install jquery. The installed version is 3.1.0

Then, the first impression is that we will use var $ = require('jquery').

Save the following code as app.js

var $ = require('jquery')
$("body").append("<p>TEST</p>");
console.log($("body").html());


Run node app.js. Prompt error:

Error: jQuery requires a window with a document

So what should we do?

On the homepage of npm's jquery installation package, we see that jsdom can be used to simulate a document.

require("jsdom").env("", function(err, window) {
if (err) {
console.error(err);
return;
}
var $ = require("jquery")(window);
$("body").append("<p>TEST</p>");
console.log($("body").html());
});

Run, the result is OK.

One thing about the above code that makes me uncomfortable is that it needs to be operated in the callback function. So what can we do without introducing jquery in the callback function?

var $ = require(&#39;jquery&#39;)(require("jsdom").jsdom().defaultView);
$("body").append("<p>TEST</p>");
console.log($("body").html());

The same operation is OK.




The above is the detailed content of How to use jQuery in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn