最近一段时间工作不是很忙,抽空学习了一下node相关的知识,打算接下来学习一下VUE框架,配合VUE框架做一个小Demo。下面是小编总结的node中几个常用的模块。
Node中的模块分为三种类型:
模块导入:
模块导出:(module.exports/exports)
在每个自定义模块的最外层,会默认添加一个闭包的函数,这个函数中会接收五个参数:
Exports:将当前模块的属性和方法导出;
__dirname:当前文件的父级目录的绝对路径;
__filename:当前文件的绝对路径
(function (module,exports,require,__dirname,__filename){
})()
let fs = require(“fs”); // 引入模块
fs.readFile(path,option,callback); // 异步读取文件
// path:当前读取文件的路径
// option:读出来数据的编码格式
// callback:回调函数;该函数有两个参数:第一个参数代表错误信息;如果没有错误,那么默认值是null;第二个参数是读出来的数据,默认是undefined。
Fs.readFileSync(path,option); // 同步读取文件;读出来的数据默认是一个JSON格式的字符串;可以通过JSON.parse转成数组
Fs.writeFile(path,data,option,callback); // 异步写入文件;当异步写入成功之后,执行这个回调;新的数据会将老的数据进行覆盖
Fs.writeFileSync(path,data,option); // 同步写入文件
Fs.appendFile(path,data,option,callback); // 向文件的末尾追加内容;如果文件路径不存在,那么会默认创建一个文件,并且把文件内容写进去;会默认的调用toString方法,将其他的数据类型转成字符串
let http = require(‘http’);
let server = http.createServer(function(req,res){ // 请求一次,该函数执行一次
// req:请求信息;当客户端请求时,会把当前请求的信息放入到这个参数中
// res:响应信息;
Console.log(req.path); // 这个是路径
Console.log(req.path); // 这个是参数
Console.log(req.path); // 主机域名
Console.log(req.path); // 返回当前路径的参数
Res.setHeader(‘Content-Type’,’text/plain;charset=utf-8’); // 设置响应头,告诉浏览器按照什么类型进行解析和渲染
res.end(‘this is a string’); // 1、结束当前请求;2、把后端整理的数据返回给客户端,数据是字符串或者buffer类型的
}
// 端口号:0-65535; http默认端口号是80,HTTPS默认端口号是443
// 让当前的服务监听8000这个端口;当客户端访问8000端口时,会触发当前server的回调函数;
Server.listen(8000,function(){
// 该回调函数只在端口成功启动时执行一次,启动失败不执行
Console.log(‘端口启动成功’);
});
let http = require(‘http’);
let url = require(‘url);
http.createServer(function(){
// url.parse:用来处理路径的,pathname:当前的路径;query:参数组合的对象
let {pathname,query} = url.parse(req.url,true);
}).listen(8000,function(){
Console.log(‘端口启动成功’);
})
Let mime = require(‘mime’);
let http = require(‘http’);
let url = require(‘url);
http.createServer(function(){
// url.parse:用来处理路径的,pathname:当前的路径;query:参数组合的对象
let {pathname,query} = url.parse(req.url,true);
// mime有个getType方法的返回值是当前文件对应的mime类型
// 解决了不同的文件类型设置不同的响应头
res.setHeader(‘Content-Type’,mime.getType(pathname));
}).listen(8000,function(){
Console.log(‘端口启动成功’);
})
常见的Mime类型
.html text/html
.css text/css
.txt text/plain
.js application/javascript
.json application/json
.png image/png
.jpg image/jpeg
Let express= require(‘express);
Let app = express(); // express执行相当于创建一个服务
App.get(‘/listen’,function(req,res){
Res.send(‘get’);
})
App.post(‘/listen2’,function(req,res){
Res.send(‘post);
})
App.all(‘/listen3’,function(req,res){
Res.send(‘all);
})
App.listen(8000,function(){
Console.log(‘端口启动成功~’);
})
如果其中一个请求发生错误,会导致整个服务崩溃。