Created
February 24, 2015 19:31
-
-
Save lizTheDeveloper/cf63993d5877c99e849e 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
var http = require("http"); | |
var url = require("url"); | |
var fs = require("fs"); | |
var router = { | |
"/" : function() { | |
return "Home" | |
}, | |
"/submit" : function (request) { | |
// write submitted info to file | |
writeNewUser(request.parsedUrl, function(){ | |
console.log("done writing file"); | |
}); | |
console.log("returning body now"); | |
return "Submit" | |
} | |
} | |
var server = http.createServer(function (request, response) { | |
logRequest(request); | |
request.parsedUrl = url.parse(request.url, true); | |
var bodyHandler = router[request.parsedUrl.pathname]; | |
if (bodyHandler) { | |
response.statusCode = 200; | |
response.write(bodyHandler(request)); | |
response.end(); | |
} else { | |
response.statusCode = 404; | |
response.end("Not Found"); | |
} | |
}); | |
function writeNewUser(user, callback) { | |
//first line | |
fs.readFile('./db.csv', function (err, fileData) { | |
//second line | |
if (err) throw err; | |
//third line | |
var fileWithConcatenatedData = fileData.toString() + user + "\n"; | |
fs.writeFile('./db.csv', fileWithConcatenatedData, function(err){ | |
//last line | |
callback(err) | |
}); | |
}); | |
} | |
function logRequest (request) { | |
console.log(request.url); | |
} | |
server.listen(3000); // listen on port 3000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment