文章目录
1 nodejs简介
Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境。 Node.js 使用了一个事件驱动、非阻塞式 I/O 的模型。 [1]
Node 是一个让 JavaScript 运行在服务端的开发平台,它让 JavaScript 成为与PHP、Python、Perl、Ruby 等服务端语言平起平坐的脚本语言。 [2] 发布于2009年5月,由Ryan Dahl开发,实质是对Chrome V8引擎进行了封装。
Node对一些特殊用例进行优化,提供替代的API,使得V8在非浏览器环境下运行得更好。V8引擎执行Javascript的速度非常快,性能非常好。Node是一个基于Chrome JavaScript运行时建立的平台, 用于方便地搭建响应速度快、易于扩展的网络应用。Node 使用事件驱动, 非阻塞I/O 模型而得以轻量和高效,非常适合在分布式设备上运行数据密集型的实时应用。
来自百度词条
nodejs底层 由c++ 语言编写
nodejs上层 由Javascript 语言编写
node中BOM、DOM不能使用,ECMAScript可以使用
node主要用来操作文件的读写,数据库的请求,处理前端ajax请求。
node完美支持ES6,所以在node环境中可以使用ES6的所有语法
2 准备工作
首先 ,我们需要先去官网下载nodejs。
在下载完成之后,我们需要在服务器环境下运行,打开服务器,新建一个js文件 js文件不能以关键字来命名。 比如:node
之后我们就可以在js文件夹里面写代码了,写好后的代码在服务器中运行,语法是这样的:
node 文件名.js
3 开启服务
在node中,所有功能均已被封装成模块,默认使用模块化开发
其中开启服务中需要用到的模块:
http模块:用来开启服务
fs模块:用来操作模块
url模块:用来解析url
querystring模块:用来解析url携带的数据
3.1http模块
//1.引入模块
const http = require("http”);
//2.开启一个http服务,接收的回调函数中,有两个返回值,req表示请求(客户端到服务端),res表示响应(服务端到客户端)
const httpObj = http.createServer((req,res)=>{…})
//创建服务成功后,每次请求都会触发createServer的回调函数
const httpObj = http.createServer((req,res)=>{
//http请求默认情况下,会多请求一次favicon.ico图标文件,如不需要可以过滤
if(req.url != "/favicon.ico"){
//可以在服务端打印信息,只要被访问就会触发
console.log("有人访问了");
//参数req有属性为url,表示当前服务被哪个url访问,打印访问服务的url
console.log("访问的地址是:" + req.url);
//如果需要向前端返回数据,而且数据需要以html的形式被解析,有两种方式:
// 1.通过head和meta标签设置字符编码
//res.write("<head><meta charset='utf-8'></head>");
// 2.通过设置请求头,设置字符编码(推荐)
res.writeHead(200,{"content-type":"text/html;charset=utf-8"})
//通过参数res的write方法,向前端返回数据,此处打印标签进行测试
res.write("<mark>晚上吃什么</mark>")
//完成此次请求的响应之后,要结束本次响应,否则前端会一直处在请求状态
res.end()
}
})
//3.监听端口地址,成功开启服务,执行回调函数...
httpObj.listen("8001","127.0.0.1",()=>{
console.log("server runing...");
});
3.2fs模块
//引入fs(文件系统)模块
const fs = require('fs’);
//调用fs模块的读取文件方法,接收三个参数:
//参数1:指定读取文件名为请求的文件名
//参数2:指定解析文件内容的编码格式,可省略
//参数3:回调函数,读取文件后执行,接收两个参数
//参数1:错误日志,或,null
//参数2:文件内容
fs.readFile("./www/index.html","utf-8",(err,fsCont)=>{
if(err){
//如果不为null,表示有错误内容,响应404
res.write("404")
}else{
//如果为null,表示找到文件,将文件作为数据响应
res.write(fsCont)
}
res.end(); //结束本次请求
})
3.3url模块
3.3.1控制台学习url模块
控制台输入node指令
- url.parse(str[, bool])
将url地址解析成为一个对象
bool代表可选参数,默认值为false,如果值为true,表示query选项是一个对象
如果只有第一个参数
url.parse('http://localhost:3000/api?course=node&word=hello#url')
控制台输出
Url {
protocol: 'http:', // 协议
slashes: true,
auth: null,
host: 'localhost:3000', // 域名 + 端口
port: '3000', // 端口号
hostname: 'localhost', // 域名
hash: '#url', // 哈希值
search: '?course=node&word=hello', // ? + 参数
query: 'course=node&word=hello', // 字符串形式的参数
pathname: '/api', // 路由 --- 标识的是哪一个页面或者哪一个接口
path: '/api?course=node&word=hello', // 路由 + search
href: 'http://localhost:3000/api?course=node&word=hello#url' }
如果传入第二个参数并且值为true
url.parse('http://localhost:3000/api?course=node&word=hello#url', true)
控制台输出
Url {
protocol: 'http:',
slashes: true,
auth: null,
host: 'localhost:3000',
port: '3000',
hostname: 'localhost',
hash: '#url',
search: '?course=node&word=hello',
query: { course: 'node', word:"hello" }, // *****************
pathname: '/api',
path: '/api?course=node&word=hello',
href: 'http://localhost:3000/api?course=node&word=hello#url' }
3.3.2url模块结合nodejs的服务器
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
// req.url为地址栏的地址
console.log(req.url)
res.writeHead(200, {
'Content-type': 'text/html;charset=utf-8'
});![e2f138544dc262a072afb9da89147a81.png](en-resource://database/1236:1)
![e2f138544dc262a072afb9da89147a81.png](en-resource://database/1236:1)
res.write('<h1>hello world</h1>');
res.write('<h1>hello node</h1>');
res.end();
});
server.listen(3000);
console.log('your server is running at http://localhost:3000')
使用node url+server.js运行,发信打印出如下信息
/api?course=node&word=hello
/favicon.ico
第一行是我们想要的,第二行是代表的浏览器中的图标,可以过滤掉它
if (req.url !== '/favicon.ico') {
console.log(req.url)
}
运行结果
/api?course=node&word=hello
如果想要获取到参数
if (req.url !== '/favicon.ico') {
console.log(req.url);
console.log(url.parse(req.url, true)); // url.parse(str, true)
}
得到结果如下
/api?course=node&word=hello
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: '?course=node&word=hello',
query: { course: 'node', word: 'hello' },
pathname: '/api',
path: '/api?course=node&word=hello',
href: '/api?course=node&word=hello' }
-
url.parse(req.url, true).query获取到参数信息
-
url.parse(req.url, true).pathname获取到路由信息
-
url.parse(req.url, true).port获取到端口号
-
url.parse(req.url, true).protocol获取到协议信息
-
url.parse(req.url, true).hostname获取到域名信息
3.4nodejs核心模块_querystring
3.4.1 控制台学习querystring
控制台输入node指令
- querystring.parse(str)
将字符串形式的参数解析成为一个对象
querystring.parse('course=node&word=hello')
输出结果为
{ course: 'node', word: 'hello' }
3.4.2 node服务器结合querystring
const http = require('http');
const url = require('url');
const querystring = require('querystring');
const server = http.createServer((req, res) => {
if (req.url !== '/favicon.ico') {
console.log(req.url)
console.log(url.parse(req.url).query)
console.log(querystring.parse(url.parse(req.url).query)) //**********************
}
res.writeHead(200, {
'Content-type': 'text/html;charset=utf-8'
});
res.write('<h1>hello world</h1>');
res.write('<h1>hello node</h1>');
res.end();
});
server.listen(3000);
console.log('your server is running at http://localhost:3000')
在真实项目中其实一般不需要使用querystring,会使用url.parse(str, url)代替