初识node.js
模块的引入
const module = require("模块名称")
模块的引入使用require,node.js中有很多模块,其中我们经常用的模块有,fs,url和http模块,
fs模块
- 文件的异步读取
fs.readFile("./html/index.html","utf-8",(err,data)=>{
console.log("err",err)
console.log("data",data)
})
fs为引入的fs模块,readFile是fs的异步读取方法,
-
fs.readFileSync是文件同步读取的方法,参数是一个url 的地址,
-
给文件命名
fs.rename('改前','改后',err=>{})
fs.renameSync("改前","改后")
fs.renameSync("./html/index.html","./html/about.html")
- fs.unlickSync删除文件。参数为文件路径,删除目录使用rmdir
http模块
const = require("http")
const http = http.createServer((req,res)=>{
//req 相当于请求报文
//res 相当于响应报文
//后端需要设置响应头 后端设置的权重高
res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"})
res.write("hello world")
res.end() //后端需要结束响应 必须写
})
app.listen(8000,()=>{
console.log("server in running...")
})
url模块
//let obj = url.parse(str) 返回值是个对象 数据如下
protocol: 'http:', 协议
slashes: true, 双斜杠
auth: null, 作者
host: 'localhost:8002', 主机
port: '8002', 端口
hostname: 'localhost', baidu
hash: '#title', 哈希(锚) search: '?username=sdfsdf&content=234234', 查询字符串
query: 'username=sdfsdf&content=234234', 数据
pathname: '/aaa', 文件路径
path: '/aaa?username=sdfsdf&content=234234', 文件路径
href: 'http://localhost:8002/aaa?username=sdfsdf&content=234234#title'