COMMONJS

COMMONJS

Node采用的Common.js规范的使用方式有3种

  1. 内置模块【API】
    • 内置模块就是默认绑定在全局变量 global 身上的方法,类似: window.location
    • 内置模块就是Node提供的内置方法,可以直接去使用,不需要安装,在官网文档/API文档中侧边栏中内容
    • 格式: const 变量 = require(‘内置模块名’)
    • 我们在项目中基本都是使用const来定义变量的,除非这个变量是改变的,采用let
  2. 第三方模块
    • 第三方: 外部的、别人 this -> 我
    • 前端第三方模块都存储在 npmjs.com
      1. 安装/第三方模块会放置到node_modules文件夹中
      • npx nrm use taobao 切换npm源为淘宝源
      • npm i request -S/-D
        • -S 表示生产环境安装
        • -D 表示开发环境安装
    1. node_modules文件夹
      • 依赖包
      • 依赖包删除: rm -rf node_modules
      • 这个删除命令是不能在cmd中用的,因为它是Linux命令
  3. 自定义模块
    • module.exports 导出一个模块,定义模块
    • require 引入一个模块
    • 自定义包上传到 npm源
      0. 自定义包必须有一个说明文件: package.json
      npm init -y
      1. npm adduser 登录账号
      2. npm publish

内置模块:

//! dns 解析域名
// require(内置模块名)
// require(dns)  错的  dns这个时候是变量
const dns = require('dns')
dns.resolve4('web-yyb.top',(err,address) => {
    console.log('address',address)
})

//! 用于加密
const crypto = require('crypto')
//* Node的内置模块是可以链式调用的,类似:jq
const hash = crypto.createHmac('sha256', '西阁')
                   .update('I love cupcakes')
                   .digest('hex');
console.log('hash',hash)

//! OS
const os = require('os')
// console.log('os',os.networkInterfaces())

//! process 进程管理
console.log('process',process.env)

第三方模块使用:

const rp = require('request-promise')
rp('https://m.duitang.com/napi/index/hot/?start=0&limit=24&more=1&include_fields=sender%2Calbum')
    .then(res => console.log('res',res))
    .catch(error => {
        if (error) throw error 
    })

自定义模块:
这里需要两个文件,Name.js和index.js
Name.js定义,index.js使用

module.exports = {
    name: '西阁',
    getName () {
        return this.name 
    },
    setName (val) {
        this.name = val
        return this.name
    }
}

index.js代码如下

// require(你要引入的模块的相对路径)
const Name = require('./Name.js')
//! Name中一个属性,两个方法
console.log(Name.name);
console.log(Name.getName());
console.log(Name.setName('Lakers'));
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值