最精简restful实现

目录

Time is short. Just show me the code!

var http = require('http');
var url = require('url');
var items = [];

/*
附上测试方法
curl -X GET http://localhost:3000
curl -X POST -d "Node should test in action" http://localhost:3000
curl -X DELETE http://localhost:3000/1
curl -X PUT -d "Pratice node every day" http://localhost:3000/1
*/

var server = http.createServer(function (req, res) {
    // method include POST,GET,DELETE,PUT
    switch (req.method) {
        case 'POST':
            var item = '';
            // convert bytes to utf-8 encoding data
            req.setEncoding('utf-8');
            // listening data event, POST data will send to server by chunk (bytes array)
            req.on('data', function(chunk) {
                item +=chunk;
            });
            req.on('end', function() {
                items.push(item);
                res.end('OK\n');
            });
            break;
        case 'GET':
            items.forEach(function(element, i) {
                res.write(i + 1 + ') ' + element + '\n');
            });
            res.end();
            break;
        case 'DELETE':
            var path = url.parse(req.url).pathname;     //get string '/1'
            var i = parseInt(path.slice(1), 10);    // convert String to Number
            if(isNaN(i)) {
                res.statusCode = 400;
                res.end('Invalid item id');
            } else if (!items[i]) {
                res.statusCode = 404;
                res.end('Item not found!');
            } else {
                items.splice(i, 1);
                res.end('delete success!\n');
            }
            break;
        case 'PUT':
            var newItem = '';
            var putPath = url.parse(req.url).pathname;
            var j = parseInt(putPath.slice(1), 10);
            if(isNaN(j)) {
                res.statusCode = 400;
                res.end('Invalid item id');
            } else if (!items[j]) {
                res.statusCode = 404;
                res.end('item not found!');
            } else {
                req.on('data', function(chunk) {
                    newItem += chunk;
                });
                items[j-1] = newItem;
                res.end('update success!');                
            }
            break;
    }
});

server.listen(3000);