因此可以寫程式為副檔名為js的檔案將它執行
2.建立檔案
hello.js
內容為
console.log("hello, world");
3.執行hello.jsnode hello.js
4.在node.js裡每個檔案都是一個獨立的module
因此要讀其他人的檔案(module)
需要使用 exports 和 require 互相溝通
exports 和 require 有好幾種寫法
下面是其中幾種
只要是符合Javascript的寫法都可
5-1.
hello_exports.js
內容為
module.exports = {
do_a : function(r) {
console.log( 'This is do_a method of hello_export module, r:' + r);
},
do_b : function(r) {
console.log( 'This is do_b method of hello_export module, r:' + r);
}
};
hello_requir.js
內容為
var dosomething = require('./hello_exports.js');
var doing_b = require('./hello_exports.js').do_b;
dosomething.do_a('Run');
doing_b('Walk');
執行hello_requir.js
node hello_requir.js
5-2.
hello_exports.js
內容為
exports.do_a = function(r) {
console.log( 'This is do_a method of hello_export module, r:' + r);
};
exports.do_b = function(r) {
console.log( 'This is do_b method of hello_export module, r:' + r);
};
hello_requir.js
內容如同5-1的hello_requir.js和執行
5-3:
hello_exports.js
內容為
module.exports = function(){
console.log( 'This is module only one method.');
};
hello_requir.js
內容為
var dosomething = require('./hello_exports.js');>
dosomething();
如同5-1的執行
0 意見:
張貼留言