Our Aim is to use jQuery with Node.js: We can use jQuery in Node.js using the jquery module.
Note: Use the ‘jquery’ module not the ‘jQuery’ module as the latter is deprecated.
Getting jQuery to work in Node.js:
Step 1 : Making the package.json file. Use the following command to create the package.json file, which keeps track of the modules and dependencies.
npm init -y
The ‘-y’ tag makes yes the default answer for all the questions asked while creating the package.json file.
Step 2: Installing the jquery module. Use the following command to install the jquery module.
npm install jquery
npm install jsdom
Step 4 :Importing the jsdom module. Use the require method to import the jsdom module.
const jsdom = require('jsdom')
Step 5: Creating a new window. We create a window with a document by creating a JSDOM object, with the HTML code as the parameter. Following code is used to create a window with a document :-
const dom = new jsdom.JSDOM("")
Step 6: Importing jQuery and providing it with a window. Once the window with a document is created, we can use the jquery module by providing it with the window we created. The following code is used to import the jquery module.
const jquery = require('jquery')(dom.window)
That’s it we have successfully loaded jquery into our Node.js application.
Example: To get a better understanding of how it works, please go through the below example :-
GeeksforGeeks Is a cool website