Zi 字媒體
2017-07-25T20:27:27+00:00
在node.js中,可以透過require()引入npm_modules中的module,當然也可以引入自己發開發的module,例如:
//預設會抓取該資料夾的index.js
var test = require('./test_module');
在module之中,一定會有許多變數或function等等需要跟主程式溝同,透過module.exports就可以達到這點
test_module/index.js
console.log("Start test module");
module.exports.text = "This is test module";
module.exports.say = function (str) {
console.log(str);
}
app.js
var test = require('./test_module');
//test_module的變數
console.log(test.text);
//test_module的function
test.say("Johnson");
或者也可以直接取代成object
test_module/index.js
module.exports = function(name, age) {
this.name = name;
this.age = age;
this.about = function() {
console.log(this.name +' is '+ this.age +' years old');
};
};
app.js
var test = require('./test_module');
var t = new test('johsnon','24');
t.about();
另外網路上有許多使用exports與module.exports的討論,由於module.exports執行時會去將global.exports取代成self.exports(node-source/lib/module.js)
所以以下這種狀況就會出錯
module.exports = {a: 1};
exports.b = 2;
有一種解法是將module.exports跟global.exports綁在一起
exports = module.exports = Object;
不過目前使用結果,如果不要混用就不會有上述問題發生
Categories: Node.js
分類
Android
AngularJS
API Blueprint
Chrome
Database
MySQL
DataStructure
Docker
Editor
Vim
Firefox
Git
GitLab
Google API
Hadoop
Language
Go
Java
JavaScript
jQuery
jQueryChart
Node.js
Vue
PHP
Laravel
ZendFramework
Python
Mac
Network
Cisco
DLink
Juniper
Oauth
Server
Apache
Share
Unix
FreeBSD
Linux
WebDesign
Bootstrap
CSS
HTML
Wordpress
Search
搜尋關鍵字:
寫了
5860316篇文章,獲得
23313次喜歡