Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJackie Jen
2,723 PointsProblem on storing json object in variable
Hi,
I have install csvtojson npm package https://www.npmjs.com/package/csvtojson. And would like to store my json object into variable so that i can use it outside of the function. Before that i convert my test1.csv file into json format. Then i run my code node index.js, and i get undefined.
Anyone can please help me figure it out what going on. much appreciate
Here is my test1.csv
id,jobtypes,created_at,job_type_ids
1,Full time,09:07.0,3,
2,Full time,59:26.4,3,
3,Permanent,08:35.1,6,
4,Full time,45:55.8,3,
5,Contract,10:17.7,4,
6,Permanent,33:35.1,6,
7,Permanent,59:39.5,6,
8,Permanent,44:13.4,6,
9,Permanent,23:58.9,6,
Below is my code index.js
var Converter = require("csvtojson").Converter;
var converter = new Converter({});
var converterFilter = new Converter({});
function convertTojson (){
converter.fromFile("./test1.csv",function(err,result){
if (err){
console.log(err);
}else{
return result;
}
});
}
console.log(convertTojson());
2 Answers
alex novickis
34,894 PointsIf you add a return "hello" just before the close of the convertTojson() function, the undefined will go away and be replaced by "hello"
You can test this sort of behavior from the console (or node) by typing in something like
function foo() {}
it will then print "undefined", since that is what the function returns
Other than that - the program does work for me
alex novickis
34,894 PointsI would probably refactor the code so that whatever is using the result is also in the callback function, or something called by the callback function
Jackie Jen
2,723 PointsJackie Jen
2,723 PointsHi,
By just return "hello" it work fine. But how can i return the result. Since it is asynchronous function which mean we don't knw when the converTojson will finish process the result and return it. There for how can i add a call back function in this scenario?