Can I run Nodejs JavaScript script in HTML document?

Is it possible to run this JavaScript code in .html document:

<script>
    function DBConnect() {
        var mysql = require('mysql');
        var mydb = mysql.createConnection({
            host: 'localhost',
            user: 'root',
            password: 'admin123',
            database: 'users'
        });

        var username = user_name.value;
        mydb.connect();

        var query = ('select passwd from peer where username=' + username);

        console.log(query);

        connection.end(function(err) {
            // The connection is terminated now
        });
    }
</script>

Because when I'm trying always got an error: Undefined "require", or how can I call this function in other f.e.: db.js? I have already script server.js, that is running from Node.js, do you think the code above should be running here?

Ignore everyone suggesting browserify. That would make sense if you had a basic understanding of the client-server architecture, and hence, had an intuition for the limitations of browserify. The answer to your question is

No.

Node.js code runs on the server. In your code you are doing things that cannot be done on the client. You should probably understand why before attempting to write code that handles sensitive information.

Using browserify, you can run some Node.js modules on the browser, but one doing such heavy I/O can't run in your browser.

So no, you can't simply take this Node.js code and try to run it in the browser. You'll have to design a proper client-server application, with the server doing all accesses to the database.

A solution for which you'd get many tutorials could for example be

  • To let your browser JavaScript code issue some Ajax requests
  • To let your server answer those requests by querying the database and send some data in JSON in the response.
  • To make the browser change the HTML using this JSON.

You could start by googling "json node.js ajax mysql", but you have a lot of study facing you.

Even if it was possible to connect to the MySQL database directly from the HTML, it is a bad idea. If you include the database credentials in the HTML, anyone who has access to that webpage can access your database and do whatever they want with it. This is a bad idea.

You are probably trying to execute Node.js JavaScript code in a browser and the require keyword isn't recognized.

To import a JavaScript file in a browser, you should use something like this:

<script src="path/to/your/JavaScript/file"></script>