【nodejs学习】3.进程管理及异步编程

进程管理

1.调用终端命令实现目录目录拷贝

var child_procress = require('child_procress');
var util = require('util');

function copy(source, target, callback){
    child_procress.exec(util.format('cp -r %s/* %s', source, target), callback);
}

copy('a', 'b', function(err){
    // ...
});

2.Process

3.Child Procress

4.Cluster

进程管理有好多东西,但是却不是能写清楚的,具体需要什么怎样运行,其实都是具体情况具体分析,需要的时候查询官方API是个不错的办法。

异步编程

事件机制和异步IO是nodejs的特点。如果不会异步编程,那岂不是说nodejs没什么意思了吗!

1.回调

function heavyCompute(n, callback){
    var count = 0, i, j;
   
    for(i = n; i > 0; --i){
        for(j = n; j > 0; --j){
            count += 1;
        }
    }
   
    callback(count);
   
}

heavyCompute(10000, function(count){
    console.log(count);
});

console.log('hello');

//100000000

//hello

上面的程序是单线程的。

setTimeout(function(){
    console.log('world');
}, 1000);

console.log('hello');

//hello

//world

setTimeout在JS规范外,由运行环境提供的特殊函数创建一个平行进程后立即返回继续执行后续代码,平行线程执行完成后通知回来继续执行回调函数。setinterval,fs.readFile都是这样异步的。

平行线程执行完成工作,通知主线程,主线程如果在忙,则不会立刻执行,而是要等到主线程空闲时才会执行相关操作。

2.代码设计模式

1)函数返回值

//同步

var output = fn1(fn2('input'));

//异步方式

fn2('input', function(output2){
    fn1(output2, function(output1){
       
    });
});

2)遍历数组

//同步
var len = arr.length, 1=0;
for(;i<len;i++){
    arr[i]=sync(arr[i]);
}

//异步

(function next(i, len, callback){
    if(i<len){
        async(arr[i], function(value){
            arr[i]=value;
            next(i+1,len,callback);
        });
    }else{
        callback();
    }
}(0, arr.length, function(){
   
}));

//如果数据数组数据可以并行处理,但是后续代码需要数据数组数据全部处理好的情况下
(function(i, len, count, callback){
    for(;i<len;++i){
        (function(i){
            async(arr[i], function(value){
                arr[i]=value;
                if(++count===len){
                    callback();
                }
            });
        });
    }
}(0, arr.length, 0, function(){
    //init finish
}));

3)异常处理

try-catch

function sync(fn){
    return fn();
}

try{
    sync(null);
}catch(err){
    console.log('err::', err.message);
}
//=>object is not a function

4)域

如果按照上面的方法写,如果是函数多层调用,那代码就太丑了,在上面贴了一个那样的例子,系统提示,代码太丑无法显示,哎,算了,去掉吧,哈哈。因此NodeJS提供domain简化异常处理。用process捕获全局异常。

process.on('uncaughtException', function(err){
    console.log('ERR::', err.message);
});
setTimeout(function(fn){
    fn();
});

function async(request, callback){
    //Do something
    asyncA(request, function(data){
        //Do something
        asyncB(request, function(data){
            //Do something
            asyncC(request, function(data)){
                // Do something
                callback(data);
            }
        });
    });
}

http.createServer(function(request, response){
    var d = domain.create();
   
    d.on('error', function(){
        response.writeHead(500);
        response.end();
    });
   
    d.run(function(){
        async(request, function(data){
            response.writeHead(200);
            response.end(data);
        });
    });
});

原文地址:https://www.cnblogs.com/renyuzhuo/p/5057929.html