独书先生 Menu

Node.js学习笔记(1)–简单的Nodejs示例,同步异步方法调用

var http = require('http');
var exec = require('child_process').exec;

//定义请求触发时的执行代码
function onRequest(request,response){
    console.log('Accept a request!');
/*    response.write('You send a request!');
    response.end();*/
    async(response);
}

//示例化一个服务器
var server = http.createServer(onRequest);

//设置监听端口
server.listen(8080);

console.log('Server is starting...');

//同步方法
function sync() {
    var time = new Date().getTime();
    while(new Date().getTime()<time + 10000);
}
//异步方法
function async(res) {
    exec('find /',{timeout:1000,maxBuffer:2048},function (err,stdout,stderr) {
        console.log('execute');
        res.writeHead(200,{'Content-Type':'text/plain','charset':'utf-8'});
        res.write(stdout);
        res.write('Find complete');
        res.end();
    });
}