• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
LilyLiya
博客园    首页    新随笔    联系   管理    订阅  订阅
Exploring Modules
module.exports; Requiring a directory
  • 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)

posted on 2021-01-31 04:24  LilyLiya  阅读(48)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3