node.js 内置模块
/*
Node.js内置了很多的模块
fs(文件系统)
path( 磁盘路径 )
http( 通信 )
使用;
-
导入
const 变量名称 = require(‘模块名称’) -
使用模块的api
*/const path = require('path') console.log(path.resolve(__dirname)) //E:\1901\01-node.js\day01\02-module
// 需求: 返回上一级?
console.log( path.resolve(__dirname,'../'))
console.log( path.join(__dirname,'../'))
/*
Node.js中第三方模块如何使用?https://www.npmjs.com/
-
安装
-
初始化生成 package.json
-
安装对应的包
举例: npm i request -g/-D/-S
名词说明:
-g -global 全局
-D / --save-dev 开发环境
-S / -save 生产环境 -
导入
request 用来做数据请求的 -
使用
去看文档(www.npmjs.com)
*/const request = require('request'); request('https://api.douban.com/v2/movie/in_theaters',function(error,response,body){ console.log('===================================='); console.log('error',error) // console.log('response',response); console.log('body',JSON.parse(body)) console.log('===================================='); })
//3. 使用
// const age = require(‘age’) X 理由: age不是内置模块或是第三方模块
const age = require('./age.js')
console.log( age.name );
console.log( age.age );
age.sex = 'man'
// 自定义发布一个包(带有一定功能,),别人可以随意下载, 使用
/*
操作流程
1.创建一个文件夹
2.创建pageage.json
Yarn init / npm init /cnpm init
快速创建 npm init -y / yarn init -y /cnpm init -y
3.注册npm仓库
www.npmjs.com注册一个账号
命令行执行 npm adduser(必须确保你当前的源是npmjs,使用nrm来切换源)
4.上传包
npm publish
注意:
1.npm源切换 nrm. npm i nrm -g
2.注意:npm账号需要邮箱认证``
总结:
- 使用Node.js实现一个web服务器
- Node.js中模块的api很多时候可以连缀(链式调用)
- http
- createServer 创建一个web静态服务器
- listen 是用来监听当前服务器
- 名词解释
- port 端口
- hostname: 域名
- request 请求, Node.js请求谁
- response 回应]
- data 数据
- encoding; 编码方式 utf8 默认utf8
- write(data,encoding) 给前台发送一个内容
- end() 发送已经结束了
中文乱码问题
解决方案一:
response.writeHead(200,{
'Content-Type': 'text/html; charset=UTF-8'
})
解决方案2:
response.write('<head> <meta charset="UTF-8"> </head>')
//
const http = require('http');
const port = 8090;
const hostname = 'localhost' // 127.0.0.1
// 格式: http.createServer(callback).listen(prot,hostname,callback)
http.createServer(function(request,response){
// response.writeHead(statusCode,options)
response.writeHead(200,{
'Content-Type': 'text/html'
})
response.write('<head> <meta charset="UTF-8"> </head>')
response.write('<h1> name:zhangsan </h1>');
response.end()
}).listen(port,hostname,function(){
//在后端控制台输出
console.log('====================================');
console.log(`服务器运行在: https: //${hostname}:${port}`);
console.log('====================================');
})
/*
url:
用来做 浏览器 地址 解析的
api:
parse : String --> Object
format: Object —> String
resolve: url拼接
完整的url构成:
https: // www.web-yyb.top: 8080 / vue / index.html ? a=1&b=2#a=10
协议: https
域名: www.127.0.0.1.com
端口: 8080
路径: www.127.0.0.1: 8080 / vue / index.html
查找字符串: a=1&b=2
哈希: #a=10
*/
const url = require(‘url’)
const urlStr = ‘https://www.127.0.0.1:8080/vue/index.html?a=1&b=2#a=10’
const urlObj = url.parse(urlStr)
const obj = {
protocol: 'https:',
slashes: true,
auth: null,
host: 'www.web-yyb.top:8080',
port: '8080',
hostname: 'www.web-yyb.top',
hash: '#a=10',
search: '?a=1&b=2',
query: 'a=1&b=2',
pathname: '/vue/index.html',
path: '/vue/index.html?a=1&b=2',
href: 'https://www.web-yyb.top:8080/vue/index.html?a=1&b=2#a=10' }
/*
Url {
protocol: 'https:',
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: '#a=10',
search: '?%20a=1&b=2',
query: '%20a=1&b=2',
pathname:
'%20//%20www.web-yyb.top:%208080%20/%20vue%20/%20index.html%20',
path:
'%20//%20www.web-yyb.top:%208080%20/%20vue%20/%20index.html%20?%20a=1&b=2',
href:
'https:%20//%20www.web-yyb.top:%208080%20/%20vue%20/%20index.html%20?%20a=1&b=2#a=10' }
*/
// format
const str = url.format(obj)
console.log( urlObj )
console.log('====================================');
console.log(str);
console.log('====================================');
// resolve
/* https://www.web-yyb.top/a/index.html
https://www.web-yyb.top/a/demo.html
https://www.web-yyb.top/b/demo.html
*/
const astr = 'https://www.web-yyb.top/a/index.html '
const bstr = url.resolve(astr,'b/demo.html') //https://www.web-yyb.top/a/b/demo.html
const cstr = url.resolve(astr,'../b/demo.html') //https://www.web-yyb.top/a/b/demo.html
console.log('====================================');
console.log(bstr);
console.log(cstr);
console.log('====================================');
/*
qs:
干什么:
进行string 和 object 的格式
功能:
类似JSON.parse || JSON.stringify
api:
parse
stringify Object —> String
escape
unescape
名词
encoding 编码
unencoding 解码
escape 中文编码
unescape 中文解码
*/
const qs = require('querystring')
const qsObj = {
protocol: 'https:',
slashes: true,
auth: null,
host: 'www.web-yyb.top:8080',
port: '8080',
hostname: 'www.web-yyb.top',
hash: '#a=10',
search: '?a=1&b=2',
query: 'a=1&b=2',
pathname: '/vue/index.html',
path: '/vue/index.html?a=1&b=2',
href: 'https://www.web-yyb.top:8080/vue/index.html?a=1&b=2#a=10'
}
//1. stringify
const qsStr = qs.stringify(qsObj)
// console.log( qsStr )\
// 2. parse
const obj = qs.parse(qsStr)
// console.log( obj )
// 3. escape
const cityUrl = ‘https://www.127.0.0.1?city=北京’
const escapeStr = qs.escape(cityUrl)
console.log( escapeStr )
//4. unescape
const cityEsUrl = 'https%3A%2F%2Fwww.web-yyb.top%3Fcity%3D%E5%8C%97%E4%BA%AC'
console.log( qs.unescape(cityEsUrl) );
/*
get方法
http
格式:
http.get(url,callback)
on
原生js如何触发事件
DOM.onclick = function(){}
名词解释:
DOM: 节点
on: 添加事件的形式
click: 事件类型
function(){}: 事件处理程序
chunk: 分片
try {} catch{} 高级编程 错误信息捕获
*/
// http.get(url,callback)
const http = require('http')
http.get('http://api.douban.com/v2/movie/in_theaters',function( res ){
//错误信息的报出
const { statusCode } = res;
const contentType = res.headers['content-type'];
let error;
if (statusCode !== 200) {
error = new Error('Request Failed.\n' +
`Status Code: ${statusCode}`);
} else if (!/^application\/json/.test(contentType)) {
error = new Error('Invalid content-type.\n' +
`Expected application/json but received ${contentType}`);
}
if (error) {
console.error(error.message);
// Consume response data to free up memory
res.resume();
return;
}
//数据处理
res.setEncoding('utf8'); // 数据的编码格式
let data = '' //保存数据
// res.on() // 事件执行
res.on('data',(chunk)=>{
data+=chunk; //将数据流累加起来
})
res.on('end',()=>{
try{
console.log( data )
}catch(e){
console.error( e.message )
}
})
}).on('error',(e)=>{
console.error(`Got error: ${e.message}`);
})