-
Notifications
You must be signed in to change notification settings - Fork 340
Express App JSON Me
Created by Rafase282
Github | FreeCodeCamp | CodePen | LinkedIn | Medium Website | E-Mail
Most of the times we're building RESTful API servers with JSON.
Write a server that, when it receives a GET, reads a file, parses it to JSON, and responds with that content to the user.
The server should respond to any GET that matches the /books resource path. As always, the port is passed in process.argv[2]
. The file to read is passed in process.argv[3]
.
Respond with:
res.json(object)
Everything should match the /books resource path.
For reading the file, use the fs module, e.g.,
fs.readFile(filename, callback)
While the parsing can be done with JSON.parse:
object = JSON.parse(string)
No need to install the fs module. It's part of the core and the Node.js platform.
var express = require('express');
var fs = require("fs");
var app = express();
app.set('json spaces', 0)
app.get('/books', function(req, res) {
fs.readFile(process.argv[3], 'utf8', function(err, data) {
if (err) throw err;
var out = JSON.parse(data);
res.json(out)
});
});
app.listen(process.argv[2]);
var express = require('express')
var app = express()
var fs = require('fs')
app.get('/books', function(req, res) {
var filename = process.argv[3]
fs.readFile(filename, function(e, data) {
if (e) return res.sendStatus(500)
try {
books = JSON.parse(data)
} catch (e) {
res.sendStatus(500)
}
res.json(books)
})
})
app.listen(process.argv[2])
Thanks for visiting, if you like this please feel free to star my repo, follow me or even contact me about contributing as it will be a lot of work and having help would be cool.
- HTML5 and CSS
- Responsive Design with Bootstrap
- Gear up for Success
- jQuery
- Basic JavaScript
- Object Oriented and Functional Programming
- Basic Algorithm Scripting
- Basic Front End Development Projects
- Intermediate Algorithm Scripting
- JSON APIs and Ajax
- Intermediate Front End Development Projects
- Claim Your Front End Development Certificate
- Upper Intermediate Algorithm Scripting
- Automated Testing and Debugging
- Advanced Algorithm Scripting
- AngularJS (Legacy Material)
- Git
- Node.js and Express.js
- MongoDB
- API Projects
- Dynamic Web Applications
- Claim Your Back End Development Certificate
- Greefield Nonprofit Project 1
- Greefield Nonprofit Project 2
- Legacy Nonprofit Project 1
- Legacy Nonprofit Project 2
- Claim your Full Stack Development Certification
- Whiteboard Coding Interview Training
- Critical Thinking Interview Training
- Mock Interview 1
- Mock Interview 2
- Mock Interview 3