0

I am new to node js and I am creating my first REST API. So I have a /module folder where I put my modules and a /routes folder where I put my routes. I am actually trying to configure these routes and one of them leads to a ressource taken from a .toml file, so I decided to use a toml parse module taken from github. Anyway my problem is rather straighforward: When I put this in my routes.js:

app.get('/toml', function(request, response){
var get_params = url.parse(request.url, true).query;
if (Object.keys(get_params).length == 0)
{
var fs = require('fs');
fs.readFile('./path/to/my/contacts.toml', function (err, data) {
var parsed = toml.parse(data);
console.log(parsed);
response.end(JSON.stringify(parsed));
});

I get the correct output in my browser (routes is called from app.js which starts a server), i.e the toml file transformed in JSON object.

However, When I try to separate my code and create a module contacts.js in order to structure my code for the future, I get a problem:

In routes.js:

app.get('/toml', function(request, response){
var get_params = url.parse(request.url, true).query;
if (Object.keys(get_params).length == 0)
{
var ret = contacts.json_parse('./path/to/my/contacts.toml');
console.log('toto a la plage');
console.log(ret);
response.setHeader('content-type', 'application/json');
response.end(ret);
}

In contacts.js:

exports.json_parse = function(file_name) {
var toml = require('toml');
var fs = require('fs');

var output = fs.readFile(file_name, function (err, data) {
var parsed = toml.parse(data);

console.log(parsed);
//console.log(data);
return JSON.stringify(parsed);
});
return output;
}

I see the log in my shell but nothing in the browser !!! It seems that the object I am trying to send is 'undifined'. I dont get it at all. I have been stuck on this for the last two days. Note that the module contacts.js is well included and communicates ok with my routes.js because I use it for other functions and it works perfectly. Thank you.

zakk8889
  • 117
  • 1
  • 8
  • @Amit I tried to rework my function the way they said in your post but did not succeed. Still stuck – zakk8889 Aug 26 '16 at 10:15
  • You can edit your question to explain your problem. Make sure you highlight why it's different from the duplicate I marked. If it is different, it will be reopened. – Amit Aug 26 '16 at 10:59
  • @Amit its not very nice to delete post like this, it took me 30min to write it down – zakk8889 Aug 26 '16 at 12:41
  • Post is not deleted, it's marked as a duplicate (because in my opinion, it is). If you think otherwise, feel free to edit your question as I explained. You may also head to [meta] and try asking for help there, just make sure you ask an on-topic question. – Amit Aug 26 '16 at 13:08

0 Answers0