Node.js模块

node.js模块:自定义模块、内置模块、第三方模块。
一.自定义模块

  1. 创建模块
    • 对象、数组、字符串、函数
  2. 导出模块
  3. 引入模块(其他页面)并使用

举例:

// 1. 创建模块
const people = {
card: 1003,
name: ‘张三’,
sex: ‘man’,
age: 20
}

// 2. 导出模块
① module.exports = people
②module.exports = {
people
}

//3.引入模块
①const people=require(./创建模块的文件地址)
②const {people}=require(./创建模块的文件地址)

使用:console.log(people.name) //张三

二.内置模块
1.内置模块直接引用
2.引入后直接使用它的api

举例:以 query string 这个内置模块为例

const qs = require(‘querystring’)
var str = ‘http://www.baidu.com/home?a=1&b=2#c=3
const obj = { ‘http://www.baidu.com/home?a’: ‘1’, b: ‘2#c=3’ }

parse //将字符串转化为对象
        console.log( qs.parse( str ) ) // { 'http://www.baidu.com/home?a': '1', b: '2#c=3' }

stringify  //将对象转为字符串
  console.log(  qs.stringify( obj ) )  //'http://www.baidu.com/home?a=1&b=2#c=3'

 escape  //将中文进行编码
   const cityStr = 'city=北京'
    console.log( qs.escape( cityStr ) )  // city%3D%E5%8C%97%E4%BA%AC

unescape  //将中文解码
           console.log( qs.unescape('city%3D%E5%8C%97%E4%BA%AC') ) //'city=北京'

第三方模块:
一般都是从npmjs.com这个网站拉取
举例:以第三方模块request为例
使用流程:
1. 安装
先创建package.json 文件
npm/cnpm i request -S/-D
-S --save //生产环境
-D --save-dev //dev development的简写 开发环境
2. 使用
request这个模块是做数据请求
3. Node.js中数据请求不存在跨域…

  接口地址:'https://m.lagou.com/listmore.json'

 const requst = require( 'require' );

request(‘https://m.lagou.com/listmore.json’,( a,b,c ) => {
console.log( ‘a’,a ) // error
console.log( ‘b’,b ) // response 返回所有结果
console.log( ‘c’,c ) // body 数据 string
})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值