最简单的模块化
index.js
require可以省略掉.js
var http = require('http');
var config = require('./config.js');
// var config = require('./config'); //可以省略掉.js
http.createServer(function(req,res){
res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"});
var data = config.str;
res.write(data);
res.end()
}).listen(8000)
config.js
var str = 'this is config';
exports.str = str;
module.exports和exports的区别
exports
tools.js
var tools = {
add:function(x,y){
return x+y;
},
sayHello:function(){
return '你好 node.js'
}
}
exports.tools = tools;
index2.js
var tools = require('./tools.js');
console.log(tools.tools.add(1,2));
console.log(tools.tools.sayHello());
module.exports
tools.js
var tools = {
add:function(x,y){
return x+y;
},
sayHello:function(){
return '你好 node.js'
}
}
module.exports = tools;
index2.js
var tools = require('./tools.js');
console.log(tools.add(1,2));
console.log(tools.sayHello());
node_modules 下的js
foo.js
var str = 'this is config';
exports.str = str;
index3.js
var foo = require('foo');
console.log(foo.str)
node_modules 下的文件夹下的.js(文件夹名和js名字一样)
bar/bar.js
var str = 'this is config';
exports.str = str;
index4.js
var bar = require('bar/bar');
console.log(bar.str)
node_modules 下的文件夹下的.js(文件夹名和js名字不一样)
nav/index.js
var str = 'this is config';
exports.str = str;
index5.js
var nav = require('nav');
console.log(nav.str)
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。