Skip to content

Instantly share code, notes, and snippets.

@lizTheDeveloper
Created March 30, 2015 18:22
Show Gist options
  • Save lizTheDeveloper/7e393ce0aae9ff85c8c1 to your computer and use it in GitHub Desktop.
Save lizTheDeveloper/7e393ce0aae9ff85c8c1 to your computer and use it in GitHub Desktop.
Another Example Server
// Create a Server
var http = require('http');
var url = require('url');
var fs = require('fs');
var router = {
"/" : function(request, response) {
response.write('<form method="GET" action="/submit">Username: <input name="username" type="text"> <input type="submit"></form>');
next();
},
"/users" : function (request, response) {
showUsers(function(users) {
response.write(users);
next();
});
},
"/submit" : function (request, response) {
var user = request.parsedUrl.query["username"];
console.log("Saving user")
saveUser(user);
response.write("Sup, " + user);
next();
}
}
var server = http.createServer(function (request, response) {
// Specify what happens when we get a request to that server
//When a request comes in...
//Parse the request
requestParse(request);
secureRequest(request);
//Figure out what the user wants based on the URL they requested
var bodyHandler = router[request.parsedUrl.pathname];
if (bodyHandler) {
response.statusCode = 200;
response.setHeader("Content-Type", "text/html");
//Based on what they want, generate some body text
bodyHandler(request, response, function(request, response) {
response.end();
};);
//Set the status of the response so we know whether or not we got the right thing, or an error
//Send the response back
console.log("Ended the response");
} else {
response.statusCode = 404;
response.end("Oh no 404");
}
});
server.listen(3000);
console.log("Listening on port 3000")
function saveUser (user) {
fs.readFile("db.csv",function (err, data) {
if (err) {
console.log(err);
} else {
var newFileContents = data + user + "\n";
fs.writeFile('db.csv', newFileContents, function (err) {
if (err) {
console.log(err);
} else {
console.log("saved user");
}
});
}
});
}
function showUsers (callback) {
fs.readFile("db.csv",function (err, data) {
if (err) {
console.log(err);
} else {
callback(data)
}
});
}
var secureRequest = function(request) {
//do something here
};
var requestParse = function(request) {
console.log(request.url);
request.parsedUrl = url.parse(request.url, true);
};
//If data has been submitted, write it to a file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment