zoukankan      html  css  js  c++  java
  • NodeJS模块的使用

    在NodeJS中,每个js文件就是一个模块,而文件路径就是模块名, 在编写每个模块时,都有require、exports、module三个预先定义好的变量可供使用。

    require函数用于在当前模块中加载和使用别的模块,其中js扩展名可省略,require多次不会重复初始化,如果传递给require函数的是NodeJS内置模块名称,不做路径解析,require('express');

    exports对象是当前模块的导出对象,用于导出模块公有方法和属性。别的模块通过require函数使用当前模块时得到的就是当前模块的exports对象。

    导入导出结合使用:

    hello.js

    //写法1
    // exports.hello=function(){
    //     console.log('hello world');
    // }
    
    
    //写法2
    function hello(){
        console.log('hello world');
    }
    exports.hello=hello;
    
    //写法3
    // this.hello=function(){
    //     console.log('hello world');
    // }

    test.js

    var me=require('./hello.js');
    me.hello();

     还有一种写法:

    hello.js

    //写法4
    module.exports=function(){
        console.log('hello world');
    }

    main.js

    var me=require('./hello.js');
    me();

    module通过module对象可以访问到当前模块的一些相关信息,但最多的用途是替换当前模块的导出对象。

    //写法1
    // exports.hello=function(){
    //     console.log('hello world');
    // }
    
    
    //写法2
    function hello(){
        console.log('hello world');
    }
    exports.hello=hello;
    
    //写法3
    // this.hello=function(){
    //     console.log('hello world');
    // }
    mordel.exports=function(){
        console.log('bad world');
    }

  • 相关阅读:
    mvc的视图渲染方式
    Numpy系列(六)- 形状操作
    Numpy系列(五)- 复制和视图
    Numpy系列(四)- 索引和切片
    Numpy系列(三)- 基本运算操作
    Numpy系列(二)- 数据类型
    Numpy系列(一)- array
    HTML参考手册
    pkuseg:一个多领域中文分词工具包
    Nginx实现JWT验证-基于OpenResty实现
  • 原文地址:https://www.cnblogs.com/tinyphp/p/4922920.html
Copyright © 2011-2022 走看看