Node.js基础使用
1. vs code 里面如何切换自定义终端?
- Ctrl+Shift+p 打开命令面板
- 搜索shell 找到:终端 选择默认Shell进行更改
2. 浏览器 vs node
异:
- node里面没有 BOM DOM
- node多了很多自带的api,Node.js中模块的API很多时候都可以连缀(链式调用)
同: - 都是chrome v8
- 都支持js
- 都支持 ECMA Script
3. 需求: sum这个方法, 我想三个参数 , 计算三个参数值?
- Node.js 命令行有时候用起来不方便
- 解决: 我们使用文件 .js
Node.js命令行退出
- ctrl+c *2
Node.js文件运行
node 文件名称(后缀可以不要)
键盘上下键可以前进和回退命令
自动监听(自动更新, 自动刷新)Node.js文件的更新和变化( 工具 nodemon supervisor)
使用淘宝镜像
- 工具安装
cnpm i nodemon -g (i==> install g ==> global) 推荐
cnpm i supervisor -g - 使用:
nodemon 文件名称
supervisor 文件名称 - 注意事项:
问题: supervisor 会出现死循环 ?
分析: 内容一致在改变
解决: vs code 开了自动保存
nvm 使用
- 安装:
nvm install vsersion
举例: nvm install v10.8.0 || nvm install 10.8.0 || nvm install latest(最新版本) - 切换Node.js版本
nvm use vsersion
举例: nvm install v10.8.0 - 查看当前电脑中 Node.js的所有版本
nvm list
前端模块化(面试题)
-
CMD ( sea.js )
-
AMD ( require.js )
-
Common.js
-
es6模块化
CMD 和 AMD
define 定义模块
Node.js中使用了Common.js规范(三类) -
内置的
例如:fs(文件系统)
path(磁盘路径)
http(通信)
使用:
1. 导入:const 变量名称 = require(‘模块名称’)
2. 使用模块的API -
第三方的
-
自定义的
前端的环境
- 开发环境
- 生产环境
- 测试环境
- 预发布环境
- 上线环境
问题: Node.js中请求数据, 需要跨域吗?
不需要跨域的
同源策略
- 为什么会出现跨域
开发中会有不同的域名和端口等出现?我们需要去获取他们的内容 - 浏览器如何组织跨域
浏览器具有安全策略 —》 同源策略实现 - 跨域的范围是?
浏览器
问题: 为什么要有 package.json?
分析: 帮助我们记录第三方的内容
即使没有node_modules也可以下载
自定义模块的发布
package.json —> 当前项目的依赖包 兵哥
package-lock.json —> 当前项目依赖包的具体信息 兵哥的具体信息
Node.js是单线程
主线程
异步队列: Node.js中异步任务, 放在异步队列
注意: 优先执行主线程中任务, 主线程任务结束后, 再去执行异步队列中任务
http模块使用
- createServer 创建一个web静态服务器
- listen 用来监听当前服务器
- 名词解释
- port 端口
- hostname 域名
- request 请求:Node.js请求谁
- response 回应
- data 数据
- encoding 编码方式 默认为utf8
- write(data,encoding) 给前台发送一个内容
- end() 发送结束
- 中文乱码问题
解决方案一:
response.writeHead(200,{‘Content-Type’:‘text/html;charset=UTF-8’})
解决方案二:
response.write(’’)
实例:
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> yanyabing : 最帅的人 </h1>');
response.end()
}).listen(port,hostname,function(){
//在后端控制台输出
console.log(`服务器运行在: https: //${hostname}:${port}`);
})
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(http)
域名: www.web-yyb.top
端口: 8080
路径: www.web-yyb.top: 8080 / vue / index.html
提交的值: a=1&b=2
哈希: #a=10 -
resolve实例
const url = require('url')
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(bstr);
console.log(cstr);
querystring模块
进行string 和 object的格式转换,类似于JSON.parse与JSON.stringify
API:
parse: string —> object
stringify: object —> string
encape: 中文编码
unencape; 中文解码
encoding,unencoding: 编码
const qs = require('querystring')
const qsObj = {
protocol: 'https:',
slashes: true,
auth: null,
}
//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.web-yyb.top?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) )
补充:http-get方法
格式:http.get(url,callback(res));
代码实例:
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}`);
})