var exec = require("child_process").exec;function start(response) {
  console.log("Request handler 'start' was called.");
  exec("ls",
    { timeout: 100000, maxBuffer: 20000 * 1024 },
    function (error, stdout, stderr) {      // function sleep(milliSeconds) {
      //   var startTime = new Date().getTime();
      //   while (new Date().getTime() < startTime + milliSeconds);
      // }
    
      // sleep(10000);
      response.writeHead(200, { "Content-Type": "text/plain" });
      response.write(stdout);
      response.end();
    });
}function upload(response) {
  console.log("Request handler 'upload' was called.");
  response.writeHead(200, { "Content-Type": "text/plain" });
  response.write("Hello Upload");
  response.end();
}exports.start = start;
exports.upload = upload;
  // function sleep(milliSeconds) {
      //   var startTime = new Date().getTime();
      //   while (new Date().getTime() < startTime + milliSeconds);
      // }
    
      // sleep(10000);这块代码取消注释后,结果upload函数也被堵塞了? 我的本意是——————模拟start被堵塞几十秒钟,不堵塞upload,结果 start和upload都被堵塞了。
这个js 文件是被router.js调用的。 curl -v http://127.0.0.1:8888/start curl -v http://127.0.0.1:8888/upload

解决方案 »

  1.   

    JS是单线程的。所以一阻塞就都阻塞了。var queue = [];
    for(let i=0;i<10;i++){
        queue.push(function(){
            console.log(i);
        })
    };
    var time = new Date().getTime();
    var a = function(){
        var _time = new Date().getTime();
        if(_time - time >= 5000){
            return false;
        }
        return true;
    };
    while(a()){// 阻塞
        var fn;
        while(queue.length){ // 执行队列
            fn = queue.shift();
            fn();
        }
    };
    while(queue.length){ // 执行阻塞解除后的执行队列
        fn = queue.shift();
        fn();
    }
    console.log('end');不知道这样是不是你想要的效果?
      

  2.   

    你的意思就是说:
    function start(response) {
      console.log("Request handler 'start' was called.");
     
     
      exec("ls",
        { timeout: 100000, maxBuffer: 20000 * 1024 },
        function (error, stdout, stderr) {
     
          // function sleep(milliSeconds) {
          //   var startTime = new Date().getTime();
          //   while (new Date().getTime() < startTime + milliSeconds);
          // }
         
          // sleep(10000);

          response.writeHead(200, { "Content-Type": "text/plain" });
          response.write(stdout);
          response.end();
        });
    }
    如果我不对那块代码取消掉注释,那么start的堵塞时间,只能 依赖于ls的时间了
      

  3.   

    http://blog.csdn.net/qq_34309305/article/details/71552543
      

  4.   


    终于明白的意思了,  js的不能够通过代码来模拟“一个事件堵塞, 另一个事件不堵塞”。只能通过js提供的异步调用,具体的堵塞时间,需要看“操作”(数据库、io,网络)。
      

  5.   

    你说的这是异步吧,除非没有其他可运行的code,他就会堵塞,如settimeout
      

  6.   


    按照这说法, 终于明白的意思了,  js的不能够通过代码来模拟“一个事件堵塞, 另一个事件不堵塞”。只能通过js提供的异步调用,具体的堵塞时间,需要看“操作”(数据库、io,网络)。 这是对的? 是说js程序员,只能使用js自身提供的来堵塞某个事件,不能够自己来堵塞某个事件,不然会堵塞所有。也就是说,js程序员的“权利”很小,是这个意思不? 
      

  7.   

    generator
    什么时候想往下执行就next next一次后会阻塞在下一个yied中 但又不影响其他代码执行 试试