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))

 

Exploring Modules

 

  • Requiring a directory
  • Exploring Modules
  • //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)

    Exploring Modules

上一篇:commonjs规范是什么?


下一篇:Node.js 模块机制