Skip to content

Instantly share code, notes, and snippets.

@sabha
Last active August 14, 2017 22:39
Show Gist options
  • Save sabha/71609f7a9242475c40814ed5ed65d07f to your computer and use it in GitHub Desktop.
Save sabha/71609f7a9242475c40814ed5ed65d07f to your computer and use it in GitHub Desktop.
Node http File system and JSON exp
const http = require('http')
const url = require("url");
const fs = require('fs');
const port = 3000
const requestHandler = (request, response) => {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received. "+(pathname === '/persons'));
var json = JSON.parse(fs.readFileSync('./persons.json', 'utf8'));
if (pathname === '/persons') {
if (request.method == 'POST') {
console.log("POST");
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
console.log(body);
json.data.push(body)
json = JSON.stringify(json); //convert it back to json
fs.writeFile('./persons.json', json, 'utf8', function(){
response.writeHead(200, {'Content-Type': 'application/json'});
response.end(JSON.stringify(body));
}); // write it back
});
}
else
{
response.writeHead(200, {'Content-Type': 'application/json'});
response.end(JSON.stringify(json));
}
}
response.end('invalid URL , try /persons');
}
const server = http.createServer(requestHandler)
server.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
{
"name": "node_http_json",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
},
"author": "",
"license": "ISC"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment