So I was wondering if it is possible to have it return data from a json file instead of data specified in the server.js?
Short Answer is yes.
Justin suggested to use this line:
1 2 3 |
res.json(lineman.grunt.file.readJSON("some-file.json")) |
However, lineman/grunt doesn’t exist errors happen, even if you include them in the function params.
This workaround did the trick.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
function readJSONFile(filename, callback) { require("fs").readFile(filename, function (err, data) { if (err) { callback(err); return; } try { callback(null, JSON.parse(data)); } catch (exception) { callback(exception); } }); } module.exports = { drawRoutes: function (app) { app.get('/api/books', function (req, res) { readJSONFile("config/api/books.json", function (err, json) { if (err) { throw err; } res.json(json); console.log(json); }); }); } }; |
Where your json files are stored here: config/api/ allowing much more freedom to switch in and out data using JSON. Nice.