標籤

2017年3月19日 星期日

Node.js-Module(導論)

重點整理
  • 什麼是module?在此引用Node.js v7.7.3 Documentation的部分內文"In Node.js, files and modules are in one-to-one correspondence (each file is treated as a separate module)."。簡而言之,匯入一個檔案就可以說是匯入一個module
  • Module可分為兩類:
    Core module,已被編譯為二進位格式,屬於Node.js資源(source)的一部分,通常會比file module優先載入。在此引用Node.js v7.7.3 Documentation的部分內文"Node.js has several modules compiled into the binary. These modules are described in greater detail elsewhere in this documentation. The core modules are defined within Node.js's source and are located in the lib/ folder. Core modules are always preferentially loaded if their identifier is passed to require(). For instance, require('http') will always return the built in HTTP module, even if there is a file by that name."
    File module,自行撰寫或由他人撰寫的.js、.json或.node檔案
  • require()可匯入core module及file module,但是file module必須明確指定檔案路徑,可以是絕對路徑"/path/.../circle.js",或是相對路徑"./circle.js",當沒有註明路徑類型時會假設其為core module或是位於node_modules資料夾中。在此引用Node.js v7.7.3 Documentation的部分內文"A required module prefixed with '/' is an absolute path to the file. For example, require('/home/marco/foo.js') will load the file at /home/marco/foo.js. A required module prefixed with './' is relative to the file calling require(). That is, circle.js must be in the same directory as foo.js for require('./circle') to find it. Without a leading '/', './', or '../' to indicate a file, the module must either be a core module or is loaded from a node_modules folder."
  • 當匯入模組成功後會傳回一個物件,包含該module的所有屬性及方法。但module中大部分的程式邏輯都視為private而無法直接被使用,除了exports及module.exports物件(object)

實作
Core module的寫法:
執行結果

File module的寫法:
執行結果

其他參考文章
佳魁資訊所出版"為什麼全世界都在學Node.js"

沒有留言:

張貼留言