关于model.exports
在模块化,采用require 语法去引入对应js文件 , 会默认执行其中的js语句 ,
单不会存在返回值 ,例如
在modal文件夹中创建 a文件 如下:
var a = 1
var b = 2
var c = 3
console.log('a+b的值为: ',a+b );
console.log('b+c的值为: ',c+b );
console.log('a+c的值为: ',a+c );
在app文件中使用 require 语法引入
// 导入express模块
var express =require('express')
// 构建app实例
const app = express()
const modal1 = require('./modal/a')
console.log('modal1',modal1);
// 构建测试路由
app.get('/',(req,res)=>{
res.send('welcome to my music!')
})
// 监听端口启动
app.listen(8081,()=>{
console.log('服务启动成功,请访问 http://127.0.0.1:8081');
})
打印结果如下 :
================> node .\app.js
a+b的值为: 3
b+c的值为: 5
a+c的值为: 4
modal1 {}
服务启动成功,请访问 http://127.0.0.1:8081
2.结论 :
在使用require 语法引入文件过程中,会将require文件执行 ,并返回一个空对象 ,并不会返回其他东西
如过需要返回内部变量 ,当采用 model方式暴露
模块暴露方式
方式1: 直接exports.name = ***
修改mode/a.js文件如下:
var a = 1
var b = 2
var c = 3
console.log('a+b的值为: ',a+b );
console.log('b+c的值为: ',c+b );
console.log('a+c的值为: ',a+c );
exports.a=a
打印结果为:
a+b的值为: 3
b+c的值为: 5
a+c的值为: 4
modal1 { a: 1 }
服务启动成功,请访问 http://127.0.0.1:8081
方式2: 直接module.exports ={ key: value }
modal/a.js文件导出方式为
module.exports= {
a,b,c
}
运行结果:
a+b的值为: 3
b+c的值为: 5
a+c的值为: 4
modal1 { a: 1, b: 2, c: 3 }
服务启动成功,请访问 http://127.0.0.1:8081
注意
console.log('赋值前',module.exports == exports ); //
console.log('赋值前module.exports',module.exports );
console.log('赋值前exports',exports);
module.exports= {
a,b,c
}
console.log('赋值后',module.exports == exports );
console.log('赋值后module.exports',module.exports );
console.log('赋值后exports',exports);
结果为:
赋值前 true
赋值前module.exports {}
赋值前exports {}
赋值后 false
赋值后module.exports { a: 1, b: 2, c: 3 }
赋值后exports {}
modal1 { a: 1, b: 2, c: 3 }
打印module的结果:
Module {
id: 'D:\\***\node\\app1\\modal\\a.js',
exports: { a: 1, b: 2, c: 3 },
parent:
Module {
id: '.',
exports: {},
parent: null,
filename: 'D:\\****\node\\app1\\app.js',
loaded: false,
children: [ [Object], [Circular] ],
paths: [ ]
},
filename: 'D:\\***\\node\\app1\\modal\\a.js',
loaded: false,
children: [],
paths: [ ]
}
modal1 { a: 1, b: 2, c: 3 }
以上即为 模块化暴露的过程 (如有错误,请见谅~)