PhilB
PhilB

Reputation: 7

Why are Node modules not loading in html file?

I am trying to load, that is, require node modules into an index.html file.

I have installed all the node modules - in /node_modules

and in the package.json file I have: "mysql": "^2.18.1",

If I create a JS file using:

const http = require('http'); const mysql = require('mysql');

(plus other relevant code)

and run that file with: node filename, I get the required output of a MYSQL table in the browser.

When I try the:

const http = require('http'); const mysql = require('mysql');

in the index.html file, I get the message: "ReferenceError: require is not defined".

Now, I know that this is a common JS message when vars are not defined or files cannot be found, but I do not understand why the modules are being found 'locally', that is when run in the terminal with the node command above, but not when the same code - const... is being used in the JS area in the html file.

In short, is there some way to specify the path to the modules in the html file that I am missing? (I have tried various things with ./ etc.) Or, is there something else wrong?

Thanks PB

Upvotes: 0

Views: 851

Answers (1)

D. Pardal
D. Pardal

Reputation: 6597

It is not possible to require Node.js modules from a webpage running inside a browser. A webpage can only access Web APIs, like the DOM.

Now, I know that this is a common JS message when vars are not defined or files cannot be found [...]

It's actually a message from the JS engine, saying that the require function was not found. Common JS is not available inside a browser either (unless you include it in your project).

Upvotes: 1

Related Questions