I want to use module.exports to move User to another folder, but it is not working
The console give this error
script.js:542 Uncaught ReferenceError: module is not defined
class User {
constructor(name, email) {
this.name = name;
this.email = email;
}
courseList = [];
getInfo() {
return {
name: this.name,
email: this.email
};
}
enrollCourse(name) {
this.courseList.push(name);
}
getCourseList() {
return this.courseList;
}
}
module.exports= User;
This in the new folder
import User from "./script";
const piyush = new User("piyush", "piyush@gmail.com");
console.log(piyush);
It is wrong way to export module.exports.User change this to this module.exports = Users; and assign your class to this Users variable. after that require it in the file where you want to use it. final code
var Users = class User {
constructor(name, email) {
this.name = name;
this.email = email;
}
courseList = [];
getInfo() {
return {
name: this.name,
email: this.email
};
}
enrollCourse(name) {
this.courseList.push(name); // in console this will as show as undefine because you not using return
// return this.courseList.push(name); // if you use return then this will show 1 means items get added in your array.
}
getCourseList() {
return this.courseList;
}
}
module.exports = Users;
this is for new folder
var Users = require("./javascript.js");
const piyush = new Users("piyush", "piyush@gmail.com");
console.log(piyush); // get constructor from your json.
console.log(piyush.getInfo()); // get getInfo from your json.
console.log(piyush.enrollCourse("cse")); // get enrollCourse from your json.
console.log(piyush.getCourseList()); // get getCourseList from your json.