my code that works..
var express=require("express"),
app=express();
class bar {
constructor()
{
this.user_name=null;
this.user_surname=null;
this.user_age=null;
}
name(user_name) {
this.user_name=user_name;
return this;
}
surname(user_surname) {
this.user_surname=user_surname;
return this;
}
age(user_age) {
this.user_age=user_age;
return this;
}
get(callback) {
var list ={};
list.uname=this.user_name;
list.usurname=this.user_surname;
list.uage=this.user_age;
callback(list);
}
}
app.get("/liste/:ext",function(req,res){
var ext=req.params.ext;
res.setHeader('Content-Type', 'application/json');
if(ext==1)
{
var newbar=new bar();
newbar.name("alex").surname("broox").age(32).get(function(result){
res.json({data:result})
})
}
if(ext==2)
{
var newbar=new bar();
newbar.name("alex2").get(function(result){
res.json({data:result})
})
}
})
app.listen(4000,function(log){
console.log("listening")
})
but..following code does not work.. with require that class from other file..
test.js
module.exports = {
class bar {
constructor()
{
this.user_name=null;
this.user_surname=null;
this.user_age=null;
}
name(user_name) {
this.user_name=user_name;
return this;
}
surname(user_surname) {
this.user_surname=user_surname;
return this;
}
age(user_age) {
this.user_age=user_age;
return this;
}
get(callback) {
var list ={};
list.uname=this.user_name;
list.usurname=this.user_surname;
list.uage=this.user_age;
callback(list);
}
}
};
app.js file.. with require that class
var express=require("express"),
app=express();
require("./test")
app.get("/liste/:ext",function(req,res){
var ext=req.params.ext;
res.setHeader('Content-Type', 'application/json');
if(ext==1)
{
var newbar=new bar();
newbar.name("alex").surname("broox").age(32).get(function(result){
res.json({data:result})
})
}
if(ext==2)
{
newbar.name("alex2").get(function(result){
res.json({data:result})
})
}
})
app.listen(4000,function(log){
console.log("listening")
})
but why does not it work...please help me..above code that works but this code that does not work..
When exporting classes in node you need to define the class first, then export the class using module.exports
followed by the name of the class you wish to export.
// test.js
class Bar {
constructor() {
this.user_name=null;
this.user_surname=null;
this.user_age=null;
}
name(user_name) {
this.user_name=user_name;
return this;
}
surname(user_surname) {
this.user_surname=user_surname;
return this;
}
age(user_age) {
this.user_age=user_age;
return this;
}
get(callback) {
var list ={};
list.uname=this.user_name;
list.usurname=this.user_surname;
list.uage=this.user_age;
callback(list);
}
}
module.exports = Bar
From there you can just require
the file and grab the class as such.
var Bar = require('./test');
var bar = new Bar();
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