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)

  • 相关阅读:
    excel数据 入库mysql 和 mysql数据 导入excel文件
    gson和fastjson将json对象转换成javaBean 简单对照
    docker入门
    jdbc 事务
    关于Java 实现抽象类的抽象方法的特性的利用---面向切面
    try}-with-resources
    关于虚拟机加载类的先后顺序测试
    MySQL api
    JS 截取字符串-全是干货
    JS截取字符串常用方法详细整理
  • 原文地址:https://www.cnblogs.com/LilyLiya/p/14351511.html
Copyright © 2011-2022 走看看