CommonJs规定
1、把公共的功能抽离成为一个单独的js文件作为一个模块,默认情况下模块里边的方法和参数,在模块外边是无法访问的。如果需要外部访问,就必须通过exports或者module.exports暴漏属性或者方法 2、在需要使用这些模块的文件中,通过require引入,后续才可进行使用

exports与module.exports区别
// app.jsconst http = require('http');const tools = require('./module/tools.js');const request = require('./module/request.js');console.log(request)http.createServer(function (req, res) {res.writeHead(200, {'Content-Type': 'text/plain'});res.write(tools.formatApi('getList'));res.end();}).listen(3000);console.log('Server running at http://127.0.0.1:3000/');// module/request.jsvar obj = {get: function () {console.log('从服务器获取数据')},post: function () {console.log('提交数据')}}module.exports = obj;// module/tools.jsfunction formatApi (path) {return `http://www.qdclub.com.cn/${path}/`}exports.formatApi = formatApi;
:::danger
node_modules中定义的模块,在引入模块的时候,路径可以不填写全路径,只填写模块所在的文件夹名称即可。
注意:
- node_moudules
- db
| db.js
| package.json // 在db目录下输入窗口输入 node init —yes生成
如果模块的入口不是index.js的情况,nodejs默认无法找到
需要在所在模块进行初始化操作,生成对应的package.json模块侯可通过直接require(‘db’)进行引用
:::

