zoukankan      html  css  js  c++  java
  • Exploring Modules

    • Working with module.exports

    当我们有很多个js文件时,在使用node的时候,我们可以定义选择js文件里的那些东西是可以共享给其他的js文件,而哪些东西不可以,可以require code from other files/modules, 例如文件系统module。

    在一个新的js文件中require我们已经定义好function的math.js文件: 

    const math = require('./math');
    console.log(math); //. output: {}

    这个时候我们不能从math.js中得到任何东西,因为math.js里面没有指定可以shared的东西,这个时候我们需要使用module.exports

    //math.js
    
    const add = (x, y) => x + y;
    
    const PI = 3.14159;
    
    const square = x => x * x;
    
    module.exports.add = add;
    module.exports.PI = PI;
    module.exports.square = square;
    

     第二种方式:整组object一起

    const add = (x, y) => x + y;
    
    const PI = 3.14159;
    
    const square = x => x * x;
    
    
    const math = {
        add: add,
        PI: PI,
        square: square
    }
    
    module.exports = math;

     第三种方式:定义的时候

    module.exports.add = (x, y) => x + y;
    module.exports.PI = 3.14159;
    module.exports.square = x => x * x;

    更简单的方式:

    const add = (x, y) => x + y;
    
    const PI = 3.14159;
    
    const square = x => x * x;
    
    exports.add = add;
    exports.square = square;
    exports.PI = PI;
    //app.js
    
    const { add, PI, square } = require('./math');
    console.log(add(1, 2))
    console.log(PI)
    console.log(square(9))

    • Requiring a directory
    • //blue.js
      module.exports = {
          name: 'blue',
          color: 'grey'
      }
      
      //janet.js
      module.exports = {
          name: 'janet',
          color: 'orange'
      }
      
      //Sadie.js
      module.exports = {
          name: 'sadie',
          color: 'black'
      }
      
      //index.js
      const blue = require('./blue')
      const sadie = require('./sadie')
      const janet = require('./janet')
      
      const allCats = [blue, sadie, janet]
      
      module.exports = allCats;

      outside the shelter folder, we have a app.js want to access to the shelter folder:

    • const cats = require('./shelter')
      
      console.log("REQUIRED AN ENTIRE DIRECTORY!", cats)

  • 相关阅读:
    计算机网络中的码元的理解
    屏幕扩展,屏幕相对位置的设置
    wireshark使用入门
    Http下载文件的登录验证
    正则-连续相同的单词
    文件系统和数据库索引用B树而不是红黑树的原因
    红黑树的突破点
    Win 10 Revit 2019 安装过程,亲自踩的一遍坑,有你想要的细节
    Java拦截器的实现原理
    根据进程数,资源数判断是否发生死锁
  • 原文地址:https://www.cnblogs.com/LilyLiya/p/14351511.html
Copyright © 2011-2022 走看看