CommonJs规定

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

自定义模块_CommonJS(Nodejs) - 图1

exports与module.exports区别

  1. // app.js
  2. const http = require('http');
  3. const tools = require('./module/tools.js');
  4. const request = require('./module/request.js');
  5. console.log(request)
  6. http.createServer(function (req, res) {
  7. res.writeHead(200, {'Content-Type': 'text/plain'});
  8. res.write(tools.formatApi('getList'));
  9. res.end();
  10. }).listen(3000);
  11. console.log('Server running at http://127.0.0.1:3000/');
  12. // module/request.js
  13. var obj = {
  14. get: function () {
  15. console.log('从服务器获取数据')
  16. },
  17. post: function () {
  18. console.log('提交数据')
  19. }
  20. }
  21. module.exports = obj;
  22. // module/tools.js
  23. function formatApi (path) {
  24. return `http://www.qdclub.com.cn/${path}/`
  25. }
  26. exports.formatApi = formatApi;

:::danger node_modules中定义的模块,在引入模块的时候,路径可以不填写全路径,只填写模块所在的文件夹名称即可。
注意:
- node_moudules
- db
| db.js
| package.json // 在db目录下输入窗口输入 node init —yes生成

如果模块的入口不是index.js的情况,nodejs默认无法找到
需要在所在模块进行初始化操作,生成对应的package.json模块侯可通过直接require(‘db’)进行引用 ::: image.png