nodejs+express 初學(三)

來源:互聯網
上載者:User

標籤:

Nodejs 的模組,nodejs中每一個js檔案都是獨立的,不用擔心他們中的變數會相互覆蓋

 模組是 Node.js 應用程式的基本組成部分,檔案和模組是一一對應的。換言之,一個
Node.js 檔案就是一個模組,這個檔案可能是 JavaScript 代碼、 JSON 或者編譯過的 C/C++ 擴充。

 

1.擷取模組

Node.js 提供了 exports 和 require 兩個對象,其中 exports 是模組公開的介面, require 用於從外部擷取一個模組的介面,即所擷取模組的 exports 對象。
eg:

  //module.js
var name;
exports.setName = function(thyName) {
  name = thyName;
};
exports.sayHello = function() {
  console.log(‘Hello ‘ + name);
};
//getmodule.js
var myModule = require(‘./module‘);
myModule.setName(‘BYVoid‘);
myModule.sayHello();


使用 module.exports = Hello 代替了 exports.Hello=Hello。在外部參考該模組時,其介面對象就是要輸出的 Hello 對象本身,而不是原先的exports。

不可以通過對 exports 直接賦值代替對 module.exports 賦值。exports 實際上只是一個和 module.exports 指向同一個對象的變數,它本身會在模組執行結束後釋放,但 module 不會,因此只能通過指定module.exports 來改變提供者




2.全域對象與全域變數

global 最根本的作用是作為全域變數的宿主

2.1 process

process 是一個全域變數,即 global 對象的屬性。它用於描述當前 Node.js 進程狀態的對象,提供了一個與作業系統的簡單介面。

process.nextTick(callback)的功能是為事件迴圈設定一項任務, Node.js 會在下次事件迴圈調響應時調用 callback。

 eg;

function doSomething(args, callback) {
  somethingComplicated(args);
  process.nextTick(callback);
}
doSomething(function onEnd() {
  compute();
});

不要使用 setTimeout(fn,0)代替 process.nextTick(callback),前者比後者效率要低得多。

nodejs+express 初學(三)

聯繫我們

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