zoukankan      html  css  js  c++  java
  • Nodejs-模块化结构

    1.模块(一个文件就是一个模块)

        

      

      获取当前脚本所在的路径
       _ _dirname
      文件路径
       _ _filename

     (1)创建模块(module1.js)

    const fs=require('fs');
    //所有的文件操作都必须是绝对路径(物理路径)
    fs.readFile(__dirname+'/../list.md',(error,content)=>{
    	if(error){
    		throw error;
    	}
    	console.log(content.toString());
    });
    

    (2)载入模块(011.js)

    const moudel1=require('./modules/module1.js');//载入模块
    

    (3执行node 011.js可以拿到module1.js中的东西

      路径位置:

      

      执行结果:

      

     2.module(模块对象)

      

      

    3.exports

      映射到module.exports的别名

      module.exports{};

      var exports=module.exports{};

    4.require

      (1)Node使用CommonJS模块规范,内置的require函数用于加载模块文件

      (2)require的基本功能是,读入并执行一个JavaScript文件,然后返回该模块的exports对象

      如果没有发现指定模块,会报错

      require不仅仅可以载入JS模块,也可以载入JSON对象(大部分用于读取配置信息)

      

    5.模块缓存

      (1)第一次加载某个模块时Node会缓存该模块。以后再加载该模块,就直接从缓存中取出该模块。

      module.exports属性不会再次执行该模块

      04.js

    //模块的缓存,setInterval中的箭头函数每隔一秒执行一次
    setInterval(()=>{
    	var date=require('./modules/module3.js');
    	console.log(date.getTime());
    },1000);
    

     module3.js

    module.exports=new Date();//导出成员
    

      

      

     (2)如何得到缓存和删除缓存

      得到缓存,通过require.cache

      require.cache记录node应用程序启动过程中所有的缓存

    //模块的缓存
    setInterval(()=>{
    	var date=require('./modules/module3.js');
    	console.log(require.cache);
    },1000);
    

      

      删除缓存,通过delete require.cache[key],一般不会清空缓存的,除非更新JSON数据的时候,要更新,就要清空缓存

    //模块的缓存
    setInterval(()=>{
    	Object.keys(require.cache).forEach((key)=>{
    		delete require.cache[key];//不能直接删除用delete require.cache,要进行遍历,把里面的成员删掉
    	});
    	var date=require('./modules/module3.js');
    	console.log(date.getTime());
    },1000);
    

      

      

  • 相关阅读:
    centos7安装mysql8 ERROR! The server quit without updating PID file
    linux桌面系统开启windows远程访问
    intellij ide 激活(转发)
    intellij ide调用一个对象所有的set方法
    linux服务器磁盘挂载
    互联网公司研发团队服务器开发工具清单
    intellij ide 集成cmder
    maven 私服上有jar包但是却下载不下来
    java开发人员win10配置
    996 icu我能为你做什么?
  • 原文地址:https://www.cnblogs.com/GumpYan/p/5796724.html
Copyright © 2011-2022 走看看