node.js 學習筆記(1)/9.26

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   使用   ar   sp   div   

node.js核心模組:

1.nodejs全域變數是global,不是window

2.process 進程對象

3.console.log() 控制台輸出

內建模組

1.util //功能不詳,貌似是繼承Sub,Base這兩個類的

   (.eg)1 util.inherits(Sub, Base); 

2.events //功能不詳

3.fs //file stream?

 (.eg)

1 var fs = require("fs"); 2 fs.readFile("file.txt", "utf-8", readFileCallBack);

 4.HTTP伺服器與用戶端

http.Server事件

http.SeverRequest\http.SeverRespnse

1 var http = require("http");2 3 function start(req, res){4     res.writeHead(200, {"Contnet-Type": "text/html"});5     res.write("<h1>NodeJs</h1>");6     res.end("<p>The End</p>")7 }8 9 http.createServer(start).listen(3000);

 

模組與包

1.建立模組 

2.Express架構(mvc)

 ------------------------------------------------------------華麗麗的分割線啊啊啊啊啊~~~~~--------------------------------------------------------------------

learning source: http://www.open-open.com/lib/view/1392611872538(此部分較為簡略)

模組:require, exports, module (key words)

require:用於在當前模組中載入和使用別的模組,傳入一個模組名,返回一個模組匯出對象。模組名可使用相對路徑(以 ./ 開頭),或者是絕對路徑(以 / 或 c:之類的盤符開頭)。另外,模組名中的 .js副檔名可以省略。以下是一個例子。

var foo = require("./foo"); //相對路徑var foo1 = require("./foo.js"); //js可以省略var foo2 = require("/home/foo.js") //絕對路徑//comparetively we also can require json,but with behind-address .jsonvar json = require("./j.json");

  

  exports: exports 對象是當前模組的匯出對象,用於匯出模組公有方法和屬性。別的模組通過 require函數使用當前模組時得到的就是當前模組的 exports對象。以下例子中匯出了一個公有方法。

exports.hello = function(){    console.log("hello world!");}

 

  module:通過 module對象可以訪問到當前模組的一些相關資訊,但最多的用途是替換當前模組的匯出對象。例如模組匯出對象預設是一個普通對象,如果想改成一個函數的話,可以使用以下方式。

module.exports = function () {    console.log(‘Hello World!‘);};
//以上代碼中,模組預設匯出對象被替換為一個函數。

  1.模組初始化 

  模組中的js代碼只在模組被使用時執行一次,並在執行過程中初始化js匯出對象 exports ,之後重複利用使用對象

  主模組:通過命令列參數傳遞給NodeJS以啟動程式的模組被稱為主模組。主模組負責調度組成整個程式的其它模組完成工作。例如通過以下命令啟動程式時,main.js就是主模組。

var counter1 = require(‘./util/counter‘);var  counter2 = require(‘./util/counter‘);//...some other operation

  counter.js存在一個私人變數,一個公有擷取方法。

var i = 0;function count(){    i++;}exports.count = count;

  在main中調用

console.log(counter1.count());console.log(counter2.count());//輸出 1, 2
part1總結:

1.安裝nodejs的本質是,把nodejs執行程式複製到一個目錄,而且這個目錄在系統PATH環境變數下,以便終端使用node執行

2.使用CMD模組系統,主模組作為程式入口,每個模組在執行過程中只初始化一次。

node.js 學習筆記(1)/9.26

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.