Use jQuery in Node. js and node. jsjquery
First, install jquery and npm install jquery. The installed version is 3.1.0.
Next, first we will use var $ = require ('jquery ').
Save the following code as app. js
Var $ = require ('jquery ') $ ("body "). append ("<div> TEST </div>"); console. log ($ ("body" pai.html ());
Run node app. js. Error message:
Error: jQuery requires a window with a document
So what should we do?
On the jquery installation package home page of npm, we can use jsdom to simulate a document.
Require ("jsdom "). env ("", function (err, window) {if (err) {console. error (err); return;} var $ = require ("jquery") (window); $ ("body "). append ("<div> TEST </div>"); console. log ($ ("body" ).html ());});
Run and the result is OK.
The above code makes it uncomfortable for me to perform operations in the callback function. So how can we introduce jquery In the callback function?
Var $ = require ('jquery ') (require ("jsdom "). jsdom (). defaultView); $ ("body "). append ("<div> TEST </div>"); console. log ($ ("body" pai.html ());
Run OK.