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('jquery')(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!