nodejs json data serving
// load up the express framework and body-parser helper
const express = require('express');
const bodyParser = require('body-parser');
// create an instance of express to serve our end points
const app = express();
// we'll load up node's built in file system helper library here
// (we'll be using this later to serve our JSON files
const fs = require('fs');
// configure our express instance with some body-parser settings
// including handling JSON data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// this is where we'll handle our various routes from
const routes = require('./routes/routes.js')(app, fs);
// finally, launch our server on port 3001.
const server = app.listen(3001, () => {
console.log('listening on port %s...', server.address().port);
});
const userRoutes = (app, fs) => {
//...unchanged ^^^
// refactored helper methods
const readFile = (
callback,
returnJson = false,
filePath = dataPath,
encoding = 'utf8'
) => {
fs.readFile(filePath, encoding, (err, data) => {
if (err) {
throw err;
}
callback(returnJson ? JSON.parse(data) : data);
});
};
const writeFile = (
fileData,
callback,
filePath = dataPath,
encoding = 'utf8'
) => {
fs.writeFile(filePath, fileData, encoding, err => {
if (err) {
throw err;
}
callback();
});
};
// READ
// Notice how we can make this 'read' operation much more simple now.
app.get('/users', (req, res) => {
readFile(data => {
res.send(data);
}, true);
});
};
module.exports = userRoutes;
// load up our shiny new route for users
const userRoutes = require('./users');
const appRouter = (app, fs) => {
// we've added in a default route here that handles empty routes
// at the base API url
app.get('/', (req, res) => {
res.send('welcome to the development api-server');
});
// run our user route module here to complete the wire up
userRoutes(app, fs);
};
// this line is unchanged
module.exports = appRouter;