0

I wrote a basic web server

If the first user open 127.0.0.1/complex

and the second user open 127.0.0.1/simple

2nd user cannot see website until 1st user complete

How can I solve this problem?

var http = require('http');
var url = require('url');
http.createServer(function (req, res) {

    var pathname = url.parse(req.url).pathname;

    res.writeHead(200, {'Content-Type': 'text/plain'});

    if(pathname=='/complex')
    {
        console.log('complex');
        complexFunction(res);
    }
    else if(pathname=='/simple')
    {
        console.log('simple');
        simpleFunction(res);
    }
}).listen(80, '127.0.0.1');


function complexFunction(res)
{
    for(var i=0; i<9999999999; i++)
    {
        var complex=200000/3;
        complex*=200;
    }
    res.end('complex');
}
function simpleFunction(res)
{
    var simple=1;
    res.end('simple');
}
CL So
  • 3,647
  • 10
  • 51
  • 95

1 Answers1

3

node.js is a single thread process and is designed for async programming. your for loop is blocking the whole process you need to split it up and make it asynchronous.

setImmediate() is one possibility or this. see: http://nodejs.org/api/timers.html#timers_setimmediate_callback_arg

var http = require('http');
var url = require('url');
http.createServer(function (req, res) {

    var pathname = url.parse(req.url).pathname;

    res.writeHead(200, {'Content-Type': 'text/plain'});

    if(pathname=='/complex')
    {
        console.log('complex');
        complexFunction(res, 9999999999);
    }
    else if(pathname=='/simple')
    {
        console.log('simple');
        simpleFunction(res);
    }
}).listen(80, '127.0.0.1');

function complexFunction(res, i)
{
   if(i >= 0)
   {
        i--;
        var complex=200000/3;
        complex*=200;

       setImmediate(function() { 
          complexFunction(res, i)
         });
    } else {
        res.end('complex');
    }
}

function simpleFunction(res)
{
    var simple=1;
    res.end('simple');
}
yuki
  • 68
  • 7