最简单的模块化

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

clipboard.png
foo.js

var str = 'this is config';
exports.str = str;

index3.js

var foo = require('foo');
console.log(foo.str)

node_modules 下的文件夹下的.js(文件夹名和js名字一样)

clipboard.png
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名字不一样)

clipboard.png
nav/index.js

var str = 'this is config';
exports.str = str;

index5.js

var nav = require('nav');
console.log(nav.str)

渣渣辉
1.3k 声望147 粉丝