Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting off in node.js getting errors Uncaught ReferenceError: module is not defined, and Uncaught ReferenceError: require is not defined

I am just starting off in Node.js and trying to use modules. I have node and npm installed and made sure everything is good to go. I will put the code bellow to show you what I am getting.

I have two files of js and here they are.

app.js:

var movies = require('./movies');
movies.avatar();

movies.js:

function printAvatar(){
  console.log("avatar pg-13");
}

function printChappie(){
  console.log("chappie pg-13");
}

module.exports.avatar = printAvatar;

Here is the html page I am running it on so I can see the console:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <script src="movies.js" type="text/javascript"></script>
    <script src="app.js" type="text/javascript"></script>
    <title></title>
  </head>
  <body>

  </body>
</html>

So basically when I run this I should be printing to the console "avatar pg-13". Except that is not happening. Here are the two errors I have received in the console.

Error1: Uncaught ReferenceError: module is not defined movie.js:9

Error2: Uncaught ReferenceError: require is not defined app.js:1

like image 937
NewbieCoder Avatar asked Jul 07 '26 09:07

NewbieCoder


1 Answers

You cannot run node code through HTML without using nw.js or similar. Open the command prompt, navigate to the folder where your code is, and type node app.js.

You could perhaps use browserify to make it runnable in the browser, but not all node code can be browserified.

like image 145
Dr. McKay Avatar answered Jul 09 '26 23:07

Dr. McKay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!