• NodeJS 模块&函数


    NodeJS 模块&函数

    nodejs的多文件操作通过模块系统实现,模块和文件一一对应。文件本身可以是javascript代码、JSON或编译过的C/C++扩展

    基本用法

    nodeJS通过exports和require两个对象实现模块通信。exports是模块对外的公开接口,require从外部获得其他模块exports的对象

    举例:

    $ tree
    .
    ├── hello.js
    └── main.js
    

    hello.js

    exports.world = function () {
        console.log('Hello World')
    }
    

    main.js

    var hello  = require('./hello')
    hello.world()
    

    把对象封装到模块中

    hello.js

    function Hello() {
        var name
        this.setName = function (s) {
            name = s
        }
        this.sayHello = function () {
            console.log("Hello, I'm "+name)
        }
    }
    
    //使用module关键字申明模块接口
    module.exports = Hello
    

    main.js

    var Hello  = require('./hello')
    var hello = new Hello()
    hello.setName("Jack")
    hello.sayHello()
    

    函数部分

    函数部分本来应该是JavaScript语法部分,这里也总结一下

    匿名函数

    function execute(someFunc, value) {
        someFunc(value)
    }
    
    execute(function (world) {
        console.log(world)
    }, "Hello world")
    

    map-reduce

    var materials = [
        'Hydrogen',
        'Helium',
        'Lithium',
        'Beryllium'
    ];
    
    // array的map函数可以用一个函数映射
    console.log(materials.map(function(material) {
        return material.length;
    }))
    
    // array的reduce函数默认使用左结合
    console.log(materials.reduce(function (x,y){
        return x +"->"+ y
    }))
    /*输出*/
    [ 8, 6, 7, 9 ]
    Hydrogen->Helium->Lithium->Beryllium
    

    常用全局量

    nodeJS的全局宿主是global,地位和浏览器中的window相当

    常用量

    • __filename:当前运行文件的绝对路径
    • __dirname:当前运行的绝对目录
    • global的process属性提供了非常丰富的属性:
      • argv:脚本参数列表
      • execPath:返回执行当前脚本的 Node 二进制文件的绝对路径
      • execArgv:返回一个数组,成员是命令行下执行脚本时,在Node可执行文件与脚本文件之间的命令行参数
      • env:返回环境变量
      • pid:进程号
      • chdir(directory):更换工作目录
      • cwd():当前目录
      • exit(code):退出,默认code为0
      • uptime:返回node已经运行的秒数
  • 相关阅读:
    django序列化器Serializers
    django中模型类变更问题
    django图书管理系统-外键字段的增删改查
    django图书管理系统模型创建
    django中使用KindEditor上传图片
    成长
    git提交代码的经验
    react项目打包
    node——moudle
    git
  • 原文地址:https://www.cnblogs.com/fanghao/p/7813904.html
Copyright © 2020-2023  润新知