2.模块/包与CommonJS

1.Node.js模块

  1. 内置的Node.js模块
const os = require('os');
console.log(os.hostname());
2.模块/包与CommonJS_第1张图片

2.第三方的Node.js模块
当需要安装第三方的包时,可以在如下网址进行查询。
https://www.npmjs.com/
npm为我们提供了包管理文件package.json,在项目目录中,首先使用npm init就会生成package.json。

npm init
npm install --save 包名(要用的包)
npm install --save-dev 包名(debug用的包)

安装的包会在项目目录/node_modules中

使用包时与第一步相同,node首先会在内部查找,没有的话就去node_modules里面查找。

3.自定义的Node.js模块


2.模块/包与CommonJS_第2张图片

在外面使用此自定义模块


2.模块/包与CommonJS_第3张图片
  • 暴露多个内容:
const hello = ()=>{
    console.log('hello');
}

let msg = '你好';

module.exports.hello = hello;
module.exports.msg = msg;

在require的时候,module.export的名字就是greeting,相当于增加了一个顶层变量,所有的函数变量都要从这个顶层变量走。

  • 暴露一个类


    2.模块/包与CommonJS_第4张图片
  • 使用
// 使用一个类
const People = require('./src/people.js');
let xiaoming = new People('小明', '12');
xiaoming.sayHello();

2.nodejs提供的核心内置模块讲解

node.js官方文档
http://nodejs.cn/api/

2.1 url模块

url模块主要用于解析url地址

const url = require('url');
console.log(url);
2.模块/包与CommonJS_第5张图片
  • url.parse(参数为url地址)
    将url字符串解析为对象
// 第二个参数,ture表示query为对象形式
console.log(url.parse('https://www.baidu.com:8080/api.php?from=li&course=node#level1',true));
2.模块/包与CommonJS_第6张图片
输出结果
  • url.format(参数为url对象)
    将对象解析为字符串
const urlObject= {
  protocol: 'https:',
  slashes: true,
  auth: null,
  host: 'www.baidu.com:8080',
  port: '8080',
  hostname: 'www.baidu.com',
  hash: '#level1',
  search: '?from=li&course=node',
  query: { from: 'li', course: 'node' },
  pathname: '/api.php',
  path: '/api.php?from=li&course=node',
  href:
   'https://www.baidu.com:8080/api.php?from=li&course=node#level1' 
}
console.log(url.format(urlObject));
结果
  • url.resolve(url1,url2)
    将两段url解析成完整的url
console.log(url.resolve('https://www.baidu.com','/api/list.php'));

2.2 querystring模块

const querystring = require('querystring');
console.log(querystring);
2.模块/包与CommonJS_第7张图片
  • querystring.stringify(参数对象)
    用于将对象转换成以&形式相连的参数字符串
console.log(querystring.stringify({name:'qian',course:['nodejs','vue.js'],from:''}));

结果:

name=qian&course=nodejs&course=vue.js&from=

也可以自定义分隔符

// 生成的字符串以,分隔
console.log(querystring.stringify({name:'qian',course:['nodejs','vue.js'],from:''},','));
name=qian,course=nodejs,course=vue.js,from=

键值对之间以:分割

// 键值之间以:分割
console.log(querystring.stringify({name:'qian',course:['nodejs','vue.js'],from:''},',',':'));
name:qian,course:nodejs,course:vue.js,from:
  • query.parse(字符串)
    将字符串转化成对象
console.log(querystring.parse('name=qian&course=nodejs&course=vue.js&from='));
console.log(querystring.parse('name=qian,course=nodejs,course=vue.js,from=',','));
console.log(querystring.parse('name:qian,course:nodejs,course:vue.js,from:',',',':'));
  • querystring.escape(字符串)
    将字符串进行编码
console.log(querystring.escape('北京'));
console.log(querystring.unescape('%E5%8C%97%E4%BA%AC'));

2.3 http模块

  • 创建服务器
// http模块

// 引用http模块
const http = require("http");

// 创建一个服务器。回调函数表示接收到请求之后做的事情
let server = http.createServer(function(req, res) {
    // req参数表示请求,res表示响应
    console.log('服务器接收到了请求'+req.url);

    //此方法向服务器发出信号,表明已发送所有响应头和主体,该服务器应该视为此消息已完成。 必须在每个响应上调用此 response.end() 方法。
    res.end();
});

//监听端口
server.listen(3000,'127.0.0.1');
2.模块/包与CommonJS_第8张图片
输入网址localhost:3000
   // 此方法用于设置响应头
    res.writeHead(200, {
        'Content-Type': 'text/plain;charset=UTF8',
    });
  • get请求
//  https Get请求
const https = require('https');
let options = {
    hostname : 'api.douban.com',
    port : 443,
    method : 'GET',
    path : '/v2/movie/top250'
} 

let request = https.request(options, (response)=>{
    console.log(response);
})

request.on('error', (error)=>{
   console.log(error);
})

request.end();
  • post请求
    在使用post请求时,将数据拆分成了众多的数据块chunk,通过特定事件,将这些小数据块有序的传递给回调函数。
const http = require ("http");
const querystring = require("querystring");
http.createServer(function(req,res) {
    // 如果请求来源是/dopost ,并且请求方法时post
    if(req.url == "/dopost" && req.method.toLowerCase() == "post"){
        // 使用post请求时,将数据拆分成了众多的数据块chunk,通过特定事件,将这些小数据块有序的传递给回调函数。
        let alldata = "";
        req.addListener("data", function(chunk) {
            alldata += chunk;
        });

        // 全部传输完毕
        req.addListener("end", function() {
            let dataString = alldata.toString();
            // 将请求数据转换为对象类型,我们就可以直接使用
            let dataObj = querystring.parse(dataString);
            res.end();
        });
    }
}).listen(80, '127.0.0.1');

你可能感兴趣的:(2.模块/包与CommonJS)