Node中文网:http://Nodejs.cn/
(一)全局变量global
- node中有一个全局变量global,是node中最大的一个对象,相当于浏览器中的window对象。
- global中的成员在使用时,可以省略global,这点也类似浏览器中的window
global中的成员
- console ,不是浏览器中的console对象,是node中的console
- process ,和进程相关的对象
- setInterval ,同理,也是node中的,不是浏览器中的
- require() ,它是全局对象global中的一个方法,用于在js文件中引入另外的文件
- __dirname ,当前执行文件的绝对路径(在js文件中使用)
- __filename ,当前执行文件的绝对路径,包含文件名(在js文件中使用)
1 console.log(123); 2 if (5 > 4) { 3 console.log('大于'); 4 } 5 global.console.log(1234); 6 global.setTimeout(() => { 7 console.log('suibian'); 8 }, 2000); 9 console.log(__dirname); 10 console.log(__filename); 11 //输出结果 12 //123 13 //大于 14 //1234 15 ///Users/lisiyi/AJAX/code/public 16 ///Users/lisiyi/AJAX/code/public/demo.js 17 //suibian
(二)Node核心模块
要使用一个模块的话必须先加载(引入)该模块。
1.path模块(处理路径模块)
- 操作文件的时候经常要对文件的路径做处理,或者获取文件的后缀,使用
path
模块。 path
是 Node 本身提供的 API,专门用来处理路径。path
仅仅用来处理路径的字符串,不一定存在对应的物理文件。
使用方法:
1 // 使用核心模块之前,首先加载核心模块 2 let path = require('path'); 3 // 或者 4 const path = require('path');
path模块中的方法:
代码举栗:
1 const path = require('path'); 2 3 // extname -- 获取文件后缀 4 console.log(path.extname('index.html')); // .html 5 console.log(path.extname('index.coffee.md')); // .md 6 7 // join -- 智能拼接路径 8 console.log(path.join('/a', 'b', 'c')); // \a\b\c 9 console.log(path.join('a', 'b', 'c')); // a\b\c 10 console.log(path.join('/a', '/b/../c')); // \a\c 11 console.log(path.join('/a', 'b', 'index.html')); // \a\b\index.html 12 console.log(path.join(__dirname, 'a', 'index.html')); // 得到一个绝对路径
2.fs模块(文件操作模块)
引入模块的时候,可以使用var、let,但是建议使用const,因为我们不希望它改变。
1 //加载模块,得到一个对象。 2 const fs = require('fs'); 3 console.log(fs);
readFile
异步读取文件。其中[编码]可选,默认输出buffer类型的数据。
1 const fs = require('fs'); 2 // fs.readFile(文件路径, [编码], 回调函数处理读取的内容); 3 fs.readFile('index.html', 'utf-8', (err, data) => { 4 //err表示是否有错误,有错误的话err表示错误信息,是一个字符串。没有错误err是undefined 5 if (err) { 6 console.log(err); //若有错误,输出错误 7 return; //阻止后续代码 8 } 9 console.log(data); //输出读取的内容 10 });
writeFile
异步写入文件。会将文件中原有的内容覆盖掉。若写入文件不存在,则会自动创建文件。
1 const fs = require('fs'); 2 // 调用writeFile方法,写入文件 3 // fs.writeFile(文件路径,写入的内容,回调函数查看是否有错误); 4 fs.writeFile('demo.txt', 'how are you', (err) => { 5 if (err) { 6 console.log(err); 7 } 8 else { 9 console.log('success'); 10 } 11 })
3.querystring模块(查询字符串处理模块)
1 //加载模块 2 const querystring = require('querystring'); 3 // parse方法是将查询字符串转换成JS对象,是querystring对象中封装的,不是JSON.parse。 4 let result = querystring.parse('id=123&name=zs&age=20'); 5 console.log(result); // { id: '123', name: 'zs', age: '20' } 6 console.log(querystring.stringify(result)); //id=123&name=zs&age=20
4.url模块
旧的API使用:
1 const url = require('url'); 2 //let res = url.parse('http://www.baidu.com:80/test.html?id=123&age=20'); 3 let res = url.parse('test.html?id=123&age=20'); //url不完整也可以解析 4 console.log(res); //解析出一个对象 5 //获取参数 6 console.log(res.query); //id=123&age=20 7 //引入querystring处理res.query 8 const querystring = require('querystring'); 9 console.log(querystring.parse(res.query)); //{ id: '123', age: '20' }
新的API使用:实例化URL的时候,必须传递一个完整的url,否则会报错
1 const myUrl = new URL('http://www.baidu.com/test.html?id=123&age=20'); 2 // const myUrl = new URL('test.html?id=123&age=20'); //报错,无效的url 3 //传两个参数组成完整的url,不会报错 4 // const myUrl = new URL('test.html?id=123&age=20', 'http://www.xyz.com'); 5 console.log(myUrl); //解析出一个对象,包含了url的各个组成部分 6 //比旧的API多了searchParams 7 console.log(myUrl.searchParams); //URLSearchParams { 'id' => '123', 'age' => '20' } 8 //获取id参数 9 console.log(myUrl.searchParams.id); //undefined 10 console.log(myUrl.searchParams.get('id')); //必须调用searchParams对象中的get方法来获取
(三)http模块(服务器处理模块)
node不同于Apache,安装完node并没有一个能够提供Web服务环境,需要使用http模块自己来搭建Web服务器。
- http是一个系统模块,让我们能够通过简单的流程创建一个Web服务器。
1.使用http模块搭建Web服务器
1 //加载http模块 2 const http = require('http'); 3 //调用http模块中的createServer方法,创建服务器 4 const server = http.createServer(); 5 //启动服务器,并且要为服务器设置端口 6 server.listen(3000, () => { 7 console.log('服务器启动了'); 8 }); 9 //添加request事件,用于处理所有的http请求 10 server.on('request', () => { 11 console.log('你的请求我收到了'); 12 });
2.如何对浏览器的请求作出响应
1 const http = require('http'); 2 const server = http.createServer(); 3 server.listen(3000, () => { 4 console.log('服务器启动了'); 5 }); 6 server.on('request', (req, res) => { 7 //事件处理函数有两个参数 8 //req表示request,所有和请求相关的信息都可以通过request对象来接收 9 //res表示response,所有和响应相关的都可以使用response对象来处理 10 console.log('你的请求我收到了'); 11 //通过res.setHeader()方法来设置响应头,若不设置会出现中文乱码 12 res.setHeader('Content-Type','text/html; charset=utf-8'); 13 //通过res对象的end方法来对浏览器作出响应 14 //res.end()方法的作用是将响应报文(行、头、体)返回给浏览器 15 res.end('你的请求我收到了'); 16 });
3.根据不同url处理不同请求
1 const http = require('http'); 2 const server = http.createServer(); 3 server.listen(8000, () => console.log('start')); 4 server.on('request', (req, res) => { 5 /* 6 req.url 表示请求的url,形如/index.html 7 req.method 表示请求方式,比如GET 8 req.headers 表示所有的请求头,是一个对象 9 */ 10 let url = req.url; 11 //判断,根据url返回信息 12 if (url === 'index.html') { 13 //读取index.html并返回内容 14 res.setHeader('content-type', 'text/html;charset=utf-8'); 15 res.end('你请求的是index.html'); 16 } 17 else if (url === '/getMsg') { 18 //读取数据并返回 19 res.setHeader('content-type', 'text/html;charset=utf-8'); 20 res.end('你请求的是getMsg接口') 21 } 22 else { 23 //服务器没有浏览器请求的文件或接口 24 res.setHeader('content-type', 'text/html;charset=utf-8'); 25 res.statusCode = 404; //不存在,设置状态码为404 26 res.end('你请求的文件不存在') 27 } 28 })
4.处理浏览器POST方式提交的数据
1 const http = require('http'); 2 const server = http.createServer(); 3 server.listen(8000, () => console.log('start')); 4 server.on('request', (req, res) => { 5 //判断是否是POST方式请求 6 if (req.method === 'POST' && req.url === '/addMsg') { 7 console.log(1234); 8 //服务器端接收数据的时候是分块接收的 9 //需要data事件,将浏览器发送过来的数据拼接到一起 10 let str = ''; 11 req.on('data', (chunk) => { 12 str += chunk; 13 }); 14 //如果已经将全部数据接收到了,则触发end事件,在这个事件中可以获取到所有数据 15 req.on('end', () => { 16 console.log(str); 17 }); 18 } 19 })
使用postman测试:
终端输出结果:
5.处理外部静态资源
为不同的文件类型设置不同的 Content-Type
- .html:text/html
- .css:text/css
- .js:application/javascript
- .jpg:image/jpg
1 response.setHeader('Content-Type', 'text/css');