Last active
February 19, 2019 13:38
-
-
Save fleepgeek/b8813b3985d20e325ced79ab22d52248 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require("fs"); | |
const http = require("http"); | |
// fs.writeFileSync("hello.txt", "Hello World"); | |
// fs.writeFile("hello.txt", country, (err) => { | |
// if(!err) { | |
// console.log("Done Writing"); | |
// res.setHeader("Location", "/"); | |
// res.statusCode = 302; | |
// res.end(); | |
// } | |
// }) | |
const server = http.createServer((req, res) => { | |
// console.log(req); | |
const url = req.url; | |
const method = req.method; | |
// console.log(url, method); | |
if(url === "/") { | |
res.write(` | |
<html> | |
<head> | |
<title>Node Home</title> | |
</head> | |
<body> | |
<h1>Welcome</h1> | |
<form method="POST" action="/create"> | |
<label for="country">Your Country</label> | |
<input type="text" id="country" name="country"> | |
<input type="submit" value="Send" /> | |
</form> | |
</body> | |
</html> | |
`); | |
res.end(); | |
} | |
if(url === "/create" && method === "POST") { | |
const body = []; | |
req.on("data", (chunk) => { | |
body.push(chunk); | |
}) | |
req.on("end", () => { | |
let parsedBody = Buffer.concat(body).toString(); | |
// console.log(parsedBody); | |
let country = parsedBody.split("=")[1]; | |
// console.log(country); | |
fs.writeFile("hello.txt", country, (err) => { | |
if(!err) { | |
console.log("Done Writing"); | |
res.setHeader("Location", "/"); | |
res.statusCode = 302; | |
res.end(); | |
} | |
}) | |
}) | |
} | |
}) | |
server.listen(3000, () => console.log("Listening on port 3000")); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment