node.js學習筆記(一) 從原理上理解NodeJs的使用場景 NPM 使用介紹

剛剛接觸Node.js,從學習網站上跟着視頻學習,也查看了一些別人學習node的筆記博客,看到一篇學習Node.js的6個步驟這邊文章,借鑑了一些的東西。javascript

第一步:打好基礎:html

  • JavaScript 的特性和語法。假如你對 JavaScript 還不熟悉的話,推薦書籍及連接:
  • Node.js 是什麼?Node.js與JavaScript的區別是什麼?
    • node.js和javascript區別仍是挺大的,1個平臺,1個是編程語言
    • javascript是客戶端編程語言,須要瀏覽器的javascript解釋器進行解釋執行前端

    • node.js是一個基於Chrome JavaScript運行時創建的平臺,它是對Google V8引擎進行了封裝的運行環境;java

    • 簡單的說node.js就是把瀏覽器的解釋器封裝起來做爲服務器運行平臺,用相似javascript的結構語法進行編程,在node.js上運行。node

  • Node.js的優勢?Node.js的缺點?
    • Node.js優勢:
      一、採用事件驅動、異步編程,爲網絡服務而設計。其實Javascript的匿名函數和閉包特性很是適合事件驅動、異步編程。並且JavaScript也簡單易學,不少前端設計人員能夠很快上手作後端設計。
      二、Node.js非阻塞模式的IO處理給Node.js帶來在相對低系統資源耗用下的高性能與出衆的負載能力,很是適合用做依賴其它IO資源的中間層服務。三、Node.js輕量高效,能夠認爲是數據密集型分佈式部署環境下的實時應用系統的完美解決方案。Node很是適合以下狀況:在響應客戶端以前,您預計可能有很高的流量,但所需的服務器端邏輯和處理不必定不少。
    • Node.js缺點:
      一、可靠性低
      二、單進程,單線程,只支持單核CPU,不能充分的利用多核CPU服務器。一旦這個進程崩掉,那麼整個web服務就崩掉了。
  • Node.js適用場景?Node.js不適用的場景?
  • Node.js的基本語法。Node.js的特性:
    • 單線程
    • 異步 IO
    • 事件驅動
  • npm 是什麼?npm的基本使用
  • REPL

 node.js的學習筆記git

1.安裝和hello。github

首先,去http://nodejs.cn/ 下載安裝,安裝很簡單,下一步下一步就哦了。而後在path中配置一下安裝目錄便可,msi會把npm(Node Package Manager)一併裝上。web

這時使用cmd命令窗口 node -v ,npm -v命令查看下安裝的版本.npm

1.一、hello,world編程

在node工程目錄中新建一個文件hello.js,裏面敲一行代碼 console.log('hello,world');

在文件下按住shift加鼠標右擊進入命令行控制檯,進入到Node.js工程目錄敲node hello.js

控制檯輸出了「hello, nodejs.」

1.二、web版的hello,world

在node工程目錄中新建一個one-demo.js,代碼以下

var http = require('http');//內置模塊引用http服務
http.createServer(function(request,response){//建立服務,向服務器發送的對象,服務器想瀏覽器返回的對象
     response.writeHead(200,  {'Content-Type':  'text/html;  charset=utf-8'});  //服務協議頭,輸出類型,編碼格式
    if(request.url!=="/favicon.ico"){  //清除第二次訪問 
        console.log('訪問');
        response.write('hello,world');//頁面輸出的內容
        response.end('');//不寫則沒有http協議尾,但寫了會產生兩次訪問 
    } 
}).listen(8000);//監聽端口
console.log('Server running at http://127.0.0.1:8000/ ')

在命令行中啓動服務,敲 node one-demo.js

而後打開瀏覽器地址欄輸入http://localhost:8000,看見頁面上輸出Hello World! 就成功了。

 2.函數調用

2.1本地函數

在node工程目錄中新建一個two-demo.js,代碼以下

var http = require('http');//必須存在
http.createServer(function(request,response){//建立服務
    response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});//協議頭
    if(request.url!=='/favicon.ico'){//清除第二次訪問
        fun1(response);
        response.end('');//協議尾
    };
}).listen('8000');
console.log('sever running at http://127.0.0.1:8000/');
//本地函數
function fun1(res){
    console.log('fun1');
    res.write('我是fun1')
}

 命令下輸出

 

 

 2.2其餘頁面函數

 在同目錄下新建js文件夾,建立fun.js

/**
function fun2(req,res){
    call('hello',req,res);
    res.write('fun2')
};
module.exports = fun2;//只支持一個函數
**/
//支持多個函數
module.exports={      
    getVisit:function(res){      
        res.write('jiayou')
    },      
    add:function(a,b){  
        b.write('hello');    
        return  a+b;   

    }      
}  

隱藏的是隻支持一個的函數

two-demo.js內容:

var http = require('http');//必須存在
var mode = require('./js/fun.js');//mode等於函數名
http.createServer(function(request,response){//建立服務
    response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});//協議頭
    if(request.url!=='/favicon.ico'){//清除第二次訪問
        // fun1(response);//本地函數
        // mode(request,response);//一個函數的
        // mode.getVisit(response);//多個函數的
        // mode.add(request,response);//多個函數的
        //----用函數名的字符串調用--
        funadd = 'add';
        mode[funadd](request,response);//等於 mode.add(request,response);等於mode['add'](request,response)
        mode['getVisit'](response);
        response.end('');//協議尾
    };
}).listen('8000');
console.log('sever running at http://127.0.0.1:8000/');
//本體函數
function fun1(res){
    console.log('fun1');
    res.write('我是fun1')
}

執行命令:

 

 

 3.調用模塊,4.路由,5.讀寫文件,6.讀圖片,7.路由改造,8.異常處理;都寫到一塊兒了,如下代碼是異常處理:

ten-demo.js

var http = require('http');//內置模塊引用http服務
var url = require('url');//內置模塊引用url服務
var router= require('./router2');//路由
var flag = require('./js/flag');//異常輸出
http.createServer(function(requset,response){//建立服務,向服務器發送的對象,服務器想瀏覽器返回的對象
    if(requset.url!=='/favicon.ico'){//清除第二次訪問
        pathname = url.parse(requset.url).pathname;//url參數
        pathname = pathname.replace(/\//,'');//正則轉換
        console.log(pathname);
        // router[pathname](response);//路由參數
        try{//異常處理適用於同步讀取
            // router[pathname](response);//對路由異常作判斷
            data = flag.exc(10);
            response.write(data.toString());
             response.end('');
        }catch(err){
            console.log('aaaaa='+err);    
            response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});        
            response.write(err.toString());        
            response.end('');
        }
    }
}).listen('8000');
console.log('服務器運行網址http://127.0.0.1:8000')

route2.js

/**
    路由+圖文輸出
**/
var readfile = require('./js/readfile');//引用模塊
function abc(res){//封裝函數
    res.writeHead(200,{'Content-Type':'text/html;charset = utf-8'});//協議頭
    function recall(data){
        res.write(data);
        res.end('');
    };
    return recall;
}
module.exports={//路由
    login:function(res){
        //採用閉包;
        recall = abc(res);
        readfile.readfile('./views/login.html',recall);
        
    },
    zhuce:function(res){
        recall = abc(res);
        readfile.readfileSync('./views/zhuce.html',recall);
        res.end('');
    },
    writeimg:function(res){
        res.writeHead(200,{'Content-Type':'image/jpeg'});//協議頭,對於圖片的輸出
        readfile.readImg('./img/pig.jpg',res);
    }
    /**
        可理解爲路由調用頁面頁面調用另外一個路由
    **/
}

readfile.js

/**
    同步和異步讀取,同步是一步一步執行;異步爲先執行其餘的,最後在執行;可同步執行
**/
var fs = require('fs');//node自帶的操做對象;
module.exports={
    readfile:function(path,recall){//異步讀取
        fs.readFile(path,function(err,data){
            if(err){
                console.log(err);               
            }else{
                console.log(data.toString());
                recall(data);
            };

        });
    },
    readfileSync:function(path,recall){//同步讀取 path讀文件的路徑
        var data = fs.readFileSync(path,'utf-8');//uft-8編碼讀取路徑賦值給data
        console.log(data);
        console.log('同步放法執行完畢')
    },
    writefile:function(path,data,recall){//異步寫入
        fs.writeFile(path,data,function(err){
            if(err){
                throw err;//異步錯誤處理
            }
            console.log(data);
        })
    },
    writefileSync:function(path,data){//同步寫入
        fs.writeFileSync(path,data);
        console.log(data);
    },
    readImg:function(path,res){//讀取輸出圖片
        fs.readFile(path,'binary',function(err,file){
            if(err){
                console.log(err);
                return;
            }else{
                console.log(path);
                res.write(file,'binary');
                res.end('')
            };
        });
    }
}

falg.js

module.exports={
    exc:function(flag){
        if(flag==0){
            throw  '我是例外'; 
        };
        return 'success'

    }
}

由於對異常進行了絕對處理。因此成功則返回success.

相關文章
相關標籤/搜索