Node 非阻塞與阻塞式IO

一、非阻塞式IO

var http=require("http");
var fs=require("fs");
http.createServer(function(req,res){
    res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"});
    res.write("服務器");
    var content="";
    fs.readFile("./data.txt",function(err,data){
        if(err) throw err;
        console.log(data.toString());
    });
    console.log(content);
    res.end();
}).listen(8100);
  • 此時在外部拿不到content值,是因爲代碼從上往下加載,fs.readFile(異步)裏面的值需要等待去拿。

  • 如果想在外面拿值,可以使用回調函數或 Promise 或 async await 去拿

使用回調函數:

var http=require("http");
var fs=require("fs");
http.createServer(function(req,res){
    res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"});
    res.write("服務器");
    var content="";
    function showData(dir,callback){
        fs.readFile("./data.txt",function(err,data){
            if(err) throw err;
            content=data.toString();
            callback(content);
        });
    }
    showData("./data.txt",function(result){
        console.log(result);
    });
    res.end();
}).listen(8100);

使用ES6的Promise:

var http=require("http");
var fs=require("fs");
http.createServer(function(req,res){
    res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"});
    res.write("服務器");
    var content="";
    var promise=new Promise(function(resolve){
        fs.readFile("./data.txt",function(err,data){
            if(err) throw err;
            content=data.toString();
            resolve(content);
        });
    });
    promise.then(function(result){
        console.log(result);
    });
    res.end();
}).listen(8100);

使用async await:

var http=require("http");
var fs=require("fs");
http.createServer(function(req,res){
    res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"});
    res.write("服務器");
    var content="";
    function showData(){
        return new Promise(function(resolve){
            fs.readFile("./data.txt",function(err,data){
                if(err) throw err;
                content=data.toString();
                resolve(content);
            });
        });
    }
    async function testResult(){
        let result=await showData();
        console.log(result);
    }
    testResult();
    res.end();
}).listen(8100);

二、阻塞式IO

var http=require("http");
var fs=require("fs");
http.createServer(function(req,res){
    res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"});
    res.write("服務器");
    var result="";
    result=fs.readFileSync("./data.txt");
    console.log(result.toString());
    res.end();
}).listen(8100);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章