nodejs常用的案例應用整理筆記

來源:互聯網
上載者:User

nodejs開啟Http服務,運行hello word

nodejs開啟一個服務是很簡單的,我們只要安裝了nodejs,隨便找個目錄,建立一個js檔案,把下面代碼複製進去,然後運行一下,就可以開啟hello word 最簡單的http服務了!

const http = require('http')

const hostname = '127.0.0.1'
const port = 3000
const server = http.createServer((req, res) => {
  res.statusCode = 200
  res.setHeader('Content-Type', 'text/plain')
  res.end('Hello World\n')
})

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`)
})
大家看到,上面代碼是運用了ES6的寫法,nodejs已經大部分支援ES6了!

nodejs 重要模組的講解及應用

//http協議模組
const http = require('http');
//url解析模組
const url = require('url');
//檔案系統模組
const fs = require("fs");
//路徑解析模組
const path = require("path");
關於以上基礎模組的常用操作命令,大家可以查看nodejs官網API,假如你覺得英文比較難懂,可以看下下面幾篇文章:

nodejs之fs模組

nodejs之Path模組

node.js之Url & QueryString模組

當然,其他的我就不寫了!我們用上面幾個模組來建立一個簡單的nodejs服務。

path 模組應用及301重新導向

//如果路徑中沒有副檔名
if(path.extname(pathName) === ''){
    //如果不是以/結尾的,加/並作301重新導向
    if (pathName.charAt(pathName.length-1) != "/"){
        pathName += "/";
        var redirect = "http://"+request.headers.host + pathName;
        response.writeHead(301, {
            location:redirect
        });
        response.end();
    }
    //添加預設的訪問頁面,但這個頁面不一定存在,後面會處理
    pathName += "index.html";
    hasExt = false; //標記預設頁面是程式自動添加的
}
fs讀取檔案清單及404頁面

fs.exists(filePath,function(exists){
    if(exists){
        response.writeHead(200, {"content-type":contentType});
        var stream = fs.createReadStream(filePath,{flags:"r",encoding:null});
        stream.on("error", function() {
            response.writeHead(500,{"content-type": "text/html"});
            response.end("<h1>500 Server Error</h1>");
        });
        //返迴文件內容
        stream.pipe(response);
    }else { //檔案名稱不存在的情況
        if(hasExt){
            //如果這個檔案不是程式自動添加的,直接返回404
            response.writeHead(404, {"content-type": "text/html"});
            response.end("<h1>404 Not Found</h1>");
        }else {
            //如果檔案是程式自動添加的且不存在,則表示使用者希望訪問的是該目錄下的檔案清單
            var html = "<head><meta charset='utf-8'></head>";

            try{
                //使用者訪問目錄
                var filedir = filePath.substring(0,filePath.lastIndexOf('\\'));
                //擷取使用者訪問路徑下的檔案清單
                var files = fs.readdirSync(filedir);
                //將訪問路徑下的所以檔案一一列舉出來,並添加超連結,以便使用者進一步訪問
                for(var i in files){
                    var filename = files[i];
                    html += "<div><a  href='"+filename+"'>"+filename+"</a></div>";
                }
            }catch (e){
                html += "<h1>您訪問的目錄不存在</h1>"
            }
            response.writeHead(200, {"content-type": "text/html"});
            response.end(html);
        }
    }
});
console.time和console.timeEnd

我們可以運用如下,輸出執行時間!

console.time('time');
console.timeEnd("time");
兩個配合使用。

nodejs中exports與module.exports的區別

nodejs我們經常用exports來建立模組,但是exports.XXX和module.exports的具體區別是什嗎?如何應用的呢?

我們來看下exports.XXX的應用:

exports.name = function() {
    console.log('My name is Haorooms');
};
在另一個檔案中你這樣引用

var rocker = require('./rocker.js');
rocker.name(); // "My name is Haorooms"
再來看下如下案例

module.exports = 'ROCK IT!';
exports.name = function() {
    console.log('My name is Haorooms');
};
再次引用執行rocker.js

var rocker = require('./rocker.js');
rocker.name(); // TypeError: Object ROCK IT! has no method 'name'
發現報錯:對象“ROCK IT!”沒有name方法

rocker模組忽略了exports收集的name方法,返回了一個字串“ROCK IT!”。由此可知,你的模組並不一定非得返回“執行個體化對象”。你的模組可以是任何合法的javascript對象--boolean, number, date, JSON, string, function, array等等。

你的模組可以是任何你設定給它的東西。如果你沒有顯式的給Module.exports設定任何屬性和方法,那麼你的模組就是exports設定給Module.exports的屬性。也就是說Module.exports才是真正的介面,exports只不過是它的一個協助工具輔助。 最終返回給調用的是Module.exports而不是exports。

假如你的模組是一個建構函式,如下:

module.exports = function(name, age) {
    this.name = name;
    this.age = age;
    this.about = function() {
        console.log(this.name +' is '+ this.age +' years old');
    };
};
可以這樣應用它:

var Rocker = require('./rocker.js');
var r = new Rocker('Ozzy', 62);
r.about(); // Ozzy is 62 years old
假如你的模組是一個數組:

module.exports = ['Lemmy Kilmister', 'Ozzy Osbourne', 'Ronnie James Dio', 'Steven Tyler', 'Mick Jagger'];
可以這樣應用它:

var rocker = require('./rocker.js');
console.log('Rockin in heaven: ' + rocker[2]); //Rockin in heaven: Ronnie James Dio
現在你明白了,如果你想你的模組是一個特定的類型就用Module.exports。如果你想的模組是一個典型的“執行個體化對象”就用exports。

github原始碼案例

上面nodejs開啟Http服務的案例我已經放到github了,大家可以看下!

http://localhost:3000/  //預設讀取index.html中的內容

http://localhost:3000/werwer/  //顯示目錄不存在

http://localhost:3000/images/  //顯示檔案清單

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.