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.