创建一个简单的server

var http = require('http');
var url = require('url');
var fs = require('fs');
var mime = {
    html: 'text/html',
    jpg: 'image/jpeg',
    png: 'image/png',
    css: 'text/css'
};

var server = http.createServer(function (request, response) {
    if (request.url != '/favicon.ico') {
        var pathname = url.parse(request.url).pathname;
        fs.readFile('.' + pathname, 'binary', function (err, data) {
            if (err) throw err;
            else {
                response.writeHead(200, {'Content-Type': mime[pathname.split('.')[1]]});
                response.write(data, 'binary');
                response.end('');
            }
        });
    }
});

server.listen(8000);
console.log('server listen on port 8000');

推荐阅读更多精彩内容