Skip to content

Instantly share code, notes, and snippets.

@oyilmaztekin
Last active December 21, 2019 12:25
Show Gist options
  • Select an option

  • Save oyilmaztekin/0d9588a32ceb07b8d90ec925289c4a46 to your computer and use it in GitHub Desktop.

Select an option

Save oyilmaztekin/0d9588a32ceb07b8d90ec925289c4a46 to your computer and use it in GitHub Desktop.
dataFromServer
const http = require("http");
const { readJSON } = require('./readFileJSON')
const server = http.createServer((req, res) => {
const pathName = req.url;
readJSON("data.json", "utf-8")
.then(data => {
if(pathName === "/"){
res.end(data);
}
if(pathName === "/getFirstUser"){
res.writeHead('200', {"Content-Type": "application/json" });
data = JSON.parse(data);
const [firstUser] = data;
res.end(JSON.stringify(firstUser));
}
if(pathName === '/getUserFriendsMoreThanOne'){
const employees = JSON.parse(data);
const employeesHaveMoreThanOne = employees.filter(el => el.friends.length > 2);
res.end(JSON.stringify(employeesHaveMoreThanOne));
}
}).catch(err => res.end(err.message))
});
server.listen(8000, "127.0.0.1", () =>
console.log("listening the port 127.0.0.1:8080")
);
const fs = require("fs");
function readJSON(fileName, type) {
return new Promise((resolve, reject) => {
fs.readFile(fileName, type, (err, data) => {
err ? reject(err) : resolve(data);
});
});
}
module.exports.readJSON = readJSON;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment