Node.js slower than Apache

前端 未结 6 888
误落风尘
误落风尘 2020-12-13 10:25

I am comparing performance of Node.js (0.5.1-pre) vs Apache (2.2.17) for a very simple scenario - serving a text file.

Here\'s the code I use for node server:

<
6条回答
  •  时光说笑
    2020-12-13 10:48

    The result of your benchmark can change in favor of node.js if you increase the concurrency and use cache in node.js

    A sample code from the book "Node Cookbook":

    var http = require('http');
    var path = require('path');
    var fs = require('fs');
    var mimeTypes = {
        '.js' : 'text/javascript',
        '.html': 'text/html',
        '.css' : 'text/css'
    } ;
    var cache = {};
    function cacheAndDeliver(f, cb) {
        if (!cache[f]) {
            fs.readFile(f, function(err, data) {
                if (!err) {
                    cache[f] = {content: data} ;
                }
                cb(err, data);
            });
            return;
        }
        console.log('loading ' + f + ' from cache');
        cb(null, cache[f].content);
    }
    http.createServer(function (request, response) {
        var lookup = path.basename(decodeURI(request.url)) || 'index.html';
        var f = 'content/'+lookup;
        fs.exists(f, function (exists) {
            if (exists) {
                fs.readFile(f, function(err,data) {
                    if (err) { response.writeHead(500);
                        response.end('Server Error!'); return; }
                        var headers = {'Content-type': mimeTypes[path.extname(lookup)]};
                        response.writeHead(200, headers);
                        response.end(data);
                    });
                return;
            }
    response.writeHead(404); //no such file found!
    response.end('Page Not Found!');
    });
    

提交回复
热议问题