I have very simple beginner problem using node.js but I cannot seem to get it to work correctly.
All I want is to be able to create objects using the 'new' operator in the index.js file.
For demonstration purposes, I have created a simple Person
object inside a Person.js file (which lies in the same directory as my index.js) like this:
class Person {
constructor() {
this._name = 'bob';
}
set name(name) {
this._name = name
}
get name() {
return this._name;
}
}
Now I want to do something like this (in the index.js file):
var p = require('./Person.js')
var bob = new p.Person()
The error message I get is telling me that Person is not a constructor:
var bob = new p.Person()
^
TypeError: p.Person is not a constructor
at Object.<anonymous> (/home/.../index.js:59:11)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3
Any help is greatly appreciated.
If you want to require or import class/function/object/anything from another JS file, you need to export that and import/require that in your current file. These are called modules.
In your case, You need to export the Person
class after creating. Otherwise JS doesn't have any reference to it. Add
module.exports = Person
below the Person
class. Now you can instantiate by
const Person = require('./person');
const p = new Person();
For the new ES6 classes you can use import/export
as well.
// Export Person Class
export default class Person {
....
}
// Now, import
import Person from './person'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With