Skip to content

Instantly share code, notes, and snippets.

@hokein
Created Sep 16, 2013
Embed
What would you like to do?
Sample code of node beginner. http://www.nodebeginner.org/index-zh-cn.html
var server = require("./server");
var router = require("./router");
var requestHandler = require("./requestHandlers");
var handle = {}
handle["/"] = requestHandler.start;
handle["/start"] = requestHandler.start;
handle["/upload"] = requestHandler.upload;
handle["/show"] = requestHandler.show;
server.start(router.route, handle);
var querystring = require("querystring");
var exec = require("child_process").exec;
var fs = require("fs");
var formidable = require("formidable");
function start(response) {
console.log("start");
var body = '<html>'+
'<head>'+
'<meta http-equiv="Content-Type" content="text/html; '+
'charset=UTF-8" />'+
'</head>'+
'<body>'+
'<form action="/upload" enctype="multipart/form-data" method="post">'+
'<input type="file" name="upload" />'+
'<input type="submit" value="Upload file" />'+
'</form>'+
'</body>'+
'</html>';
response.writeHead(200, {"Content-Type":"text/html"});
response.write(body);
response.end();
}
function upload(response, request) {
console.log("upload");
var form = new formidable.IncomingForm({uploadDir:"/tmp"});
form.parse(request, function(error, fields, files){
console.log("parsing done");
fs.renameSync(files.upload.path, "/tmp/test.png");
response.writeHead(200, {"Content-Type": "text/html"});
response.write("received image:<br/>");
response.write("<img src='/show' />");
response.end();
});
}
function show(response) {
console.log("show picture Request handler");
fs.readFile("/tmp/test.png", "binary", function(error, file){
if (error) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(error + "\n");
response.end();
}
else {
response.writeHead(200, {"Content-Type": "image/png"});
response.write(file, "binary");
response.end();
}
});
}
exports.start = start;
exports.upload = upload;
exports.show = show;
function route(handle, pathname, response, request) {
console.log("About to route a request" + pathname);
if (typeof handle[pathname] === 'function') {
handle[pathname](response, request);
} else {
console.log("Error: not function type.");
}
}
exports.route = route;
var http = require("http");
var url = require("url");
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
route(handle, pathname, response, request);
}
var server = http.createServer(onRequest);
server.listen(8888);
}
exports.start = start;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment