How to Use jQuery in Node. js and Node. js
Want to use jQuery in NodeJs?
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").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").html());
Run OK.
The above is all the content shared in this article. I hope it will be helpful for you to learn node. js.