Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export class instance in Node?

Let's say, i have a class instance

const User = require(./User);

const id = '123456',
secret   = '8787';

const user = new User(id, secret)

module.exports = user;

The problem is that whenever i import user, it just returns an empty object.
Why is this occurring and what should i do in this case?

This is what i'm using for testing

index.js file

const OAuthClient = require('disco-oauth'); //class disco-oauth

const credential = require('./credential.json');

//class instance
const oauthclient = new OAuthClient(credential.id,credential.secret); 

console.log(oauthclient); //Working fine in here

module.exports = oauthclient; //exporting instance  

test.js file

const oauthclient = require('./index')
console.log(oauthclient) //prints {}
like image 502
Blayke Avatar asked Jul 02 '26 23:07

Blayke


1 Answers

you should make file with name User.js and copy this code :

class user {
    constructor(id, secret){
        this.id= id,
        this.secret=secret
    }
 }

 module.exports = user;

and your file is ok for require User class (yourFile.js)

const User = require(./User);

const id = '123456',
secret   = '8787';

const user = new User(id, secret)

module.exports = user;

and you can make test.js file for import this user (yourFile.js) :

const user = require('./yourFile.js')
console.log(user)
like image 184
mohammad javad ahmadi Avatar answered Jul 05 '26 13:07

mohammad javad ahmadi



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!