node是一个内置平台,内置了很多的模块可以使用
模块必须引入才可以使用----require引用
fs--文件系统模块
fs.readFile()----对文件进行读取
语法:
fs.readFile(path[,option],callback)
path:文件路径
option:编码格式,默认是utf-8
callback:回调函数---回调函数中有两个参数(错误信息,文件内容)
const fs=require('fs')
fs.readFile('./文件.txt','utf8',function(err,data){
if (err) {
console.log("文件读取失败"+err.message);
}else{
console.log(data);
}
})
fs.writeFile()----向文件中写入内容
fs.writeFile(path,value[,option],callback)
path:文件路径
value:写入的内容
option:编码格式,默认是utf-8
callback:回调函数---回调函数中有两个参数(错误信息,文件内容)
const fs=require('fs')
fs.writeFile('./文件.txt','写入的内容','utf8',function(err){
if (err) {
console.log("写入失败");
}else{
console.log("写入成功");
}
})
这样写入新的内容会把文件原本的内容覆盖,
解决覆盖问题
//第一种
const fs=require('fs')
fs.writeFile('./文件.txt','新写入内容',{flag:'a'},function(err){
if (err) {
console.log("写入失败");
}else{
console.log("写入成功");
}
})
//第二种
fs.appendFile('./文件.txt','新写入内容',function(){
})
path---路径模块
__dirname---获取当前文件所处的文件夹的完整路径。是文件夹!
path.join()---拼接路径,可以将多个路径片段拼接在一起
语法:
path.join(路径1,路径2,路径3)
path.extname()---获取当前路径中文件的扩展名
path.extname(路径)
path.basename()---获取当前路径的文件名
path.basename(路径,扩展名)
http模块
http模块可以快速的创建一个web服务器
导入内置模块http
创建web服务器
监听request请求
监听端口
const http=require('http')
const server=http.createServer()
server.on('request',function(req,res){
console.log('我被请求了');
})
server.listen('8080',function(){
console.log('http://127.0.0.1:8080');
})
req,res
req---有关客户端的数据信息,请求对象
res----关于响应的信息,响应对象
req.url:请求路径
req.method:请求方式
res.end:响应页面
const http=require('http')
const server=http.createServer()
server.on('request',function(req,res){
res.end("张三")
})
server.listen('8080',function(){
console.log('http://127.0.0.1:8080/');
})