I'm really new to node.js and having a bit of a problem with objects. Lets say I have two files, one called printer.js and another called database.js. printer.js prints the results database returns. printer.js looks like this:
var db = require("./database")
db.getStations(dbReturn);
function dbReturn(stations) {
for(var i = 0; i < stations.length; i++) {
console.log('id: ' + stations.id);
}
}
and my database.js looks like this:
function getStations(callback){
var listOfStations = [];
for(var index = 0; index < 10; index++) {
var station = new Station(index);
listOfStations[index] = station;
}
callback(listOfStations);
}
function Station(id){
this.id = id;
}
exports.getStations = getStations;
I would just like to mention that Station class has a lot more members than that. But the problem here is that I cannot access the members from the Station objects I created in database.js from printer.js. I am having quite a bit of trouble figuring out how to do this. I have learned how to create a new object of Station in printer.js by exporting Station, but I still can't access the members of an object I created somewhere else! It just spits out 10 x "id: undefined"
I have been suggested to do something similar to this:
database.prototype.getStations = function(callback) {
//...
}
database.prototype.Station = function(id) {
//...
}
module.exports = database;
But this does not seem to work since it just tells me that database is undefined. What am I doing wrong here?
You're not accessing the stations by index in your for loop.
Change this in printer.js:
console.log('id: ' + stations.id);
to:
console.log('id: ' + stations[i].id);