2

Hello i am beginner in JavaScript. I am trying to access the functions of user.js in script.js but it is throwing error i have attached ss also, and below is the implementation of what I am doing.

I have create 4 files

index.js (starting file):

const express = require("express");
const app = express();
const path = require("path");
const { getUserName, getRoomUsers } = require("./utils/user");
const port = process.env.PORT || 3030;
app.set("view engine", "ejs");
app.use(express.static(path.join(__dirname, "public")));
app.use("/home", express.static("public"));
app.get("/home/welcome", (req, res) => {
  res.render("home");
});
app.get("/", (req, res) => {
  res.send("Welcomme to startup page!!");
});

app.listen(port);

home.ejs (in /views):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>welcome to home page</h1>
    <script src="script.js"></script>

</body>
</html>

user.js (in /utils):

let user = [];
function getUserName(id, room) {
  const obj = users.find((user) => user.room === room && user.id === id);
  return obj.username;
}
function getRoomUsers(room) {
  return users.filter((user) => user.room === room);
}
function userJoin(id, username, room) {
  const user = { id, username, room };
  users.push(user);
  return user;
}
module.exports = {
  userJoin,
  getRoomUsers,
  getUserName,
};

script.js (in /public):

const { getUserName, getRoomUsers } = require('./../utils/user.js')
getRoomUsers("abcd")

on running this i am getting the following error

enter image description here

how can i access the user.js functions in script.js

James Z
  • 12,209
  • 10
  • 24
  • 44
Sachin
  • 55
  • 1
  • 5
  • You don't use `require()` in client-side scripts, you use `import`. And the script has to have the `type="module"` attribute. – Barmar Jul 08 '21 at 16:21

2 Answers2

3

require is not JavaScript native method. Which is of Node.js

Please see: https://stackoverflow.com/a/9901097/16351248

And, you could use native JavaScript method: import

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

Praveen
  • 187
  • 6
  • using import does not help. I still get the same error because the package I am trying to import ALSO has require inside it – John Henckel Apr 16 '23 at 20:47
3

require and module.exports are features of CommonJS modules which Node.js supports but browsers do not.

Modern browsers support ES6 modules (which use import and export) so you could rewrite your modules in that format. MDN has a guide.

Alternatively you could use a tool like Parcel or Webpack to bundle your modules into a single browser-compatible JS file which you can provide to browsers.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335