简体   繁体   中英

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

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.

您可以在浏览器上使用require ,让我们尝试用browserify进行验证,或者在终端上使用node命令运行代码

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM