当前位置:网站首页>Nodejs服务端
Nodejs服务端
2022-08-09 10:03:00 【高桥靓仔】
Nodejs服务端
一、http模块
//引入http模块
const http = require('http');
//创建http服务
http.createServer((request, response) => {
console.log(request.url)//获取url
//设置响应头
response.writeHead(200, {
'Content-Type': 'text/plain;charset="utf-8"' })
//结束响应并返回给客户端
response.end('Hello 哈哈哈')
}).listen(8039, () => console.log('Server running at http://localhost:8039/'))
//监听端口为8039
二、url模块
var url = require('url')
//默认第二个参数为false(query属性不转换成json)
console.log(url.parse('http://user:[email protected]:8080/p/a/t/h?skip=0&limit=10#hash'))
Url {
protocol: 'http:',//传输协议
slashes: true,//slashes指的是 如果 protocol 协议冒号后面跟着两个 ASCII 斜杠字符(/)
auth: 'user:pass',//作者
host: 'sub.host.com:8080',//host 比 hostname多端口
port: '8080',//端口号
hostname: 'sub.host.com',
hash: '#hash',//hash锚点
search: '?skip=0&limit=10',//search比query多?
query: 'skip=0&limit=10',//当第二个参数为true时,query属性值为一个参数对象
pathname: '/p/a/t/h',//path比pathname多后面参数
path: '/p/a/t/h?skip=0&limit=10',
href: 'http://user:[email protected]:8080/p/a/t/h?skip=0&limit=10#hash',//href是完整路径
}
//第二个参数为true(query属性转换成json)
console.log(url.parse('http://user:[email protected]:8080/p/a/t/h?skip=0&limit=10#hash',true))
Url {
protocol: 'http:',
slashes: true,
auth: 'user:pass',
host: 'sub.host.com:8080',
port: '8080',
hostname: 'sub.host.com',
hash: '#hash',
search: '?skip=0&limit=10',
query: [Object: null prototype] {
skip: '0', limit: '10' },
pathname: '/p/a/t/h',
path: '/p/a/t/h?skip=0&limit=10',
href: 'http://user:[email protected]:8080/p/a/t/h?skip=0&limit=10#hash'
}
三、fs模块
1】fs.stat
检测是文件还是目录
var fs = require('fs')
fs.stat('./html',(err,data)=>{
if(err){
console.log(err);
return;
}
console.log(`是文件:${
data.isFile()}`)
console.log(`是目录:${
data.isDirectory()}`)
})
2】fs.mkdir
创建目录
fs.mkdir(path,[mode],[callback])
- Path:将创建的目录路径
- Mode:目录权限(读写权限),默认777
- Callback:回调,传递异常参数err
var fs = require('fs')
fs.mkdir('./css',err=>{
if(err){
console.log(err);
return;
}
console.log('创建成功')
})
3】fs.writeFile
创建文件并写入内容(或替换文件并写入内容)
fs.writeFile(filename,data,[option],[callback]
- Filename:(String)文件名称
- Data:(String|Buffer)将要写入的内容
- Option:(Object)option数组对象包含:
- Encoding:(String)默认
utf8
,当data使buffer时,该值应该为ignored
。 - Mode:(Number)文件读写权限,默认值为
438
- Flag:(String)默认值为
'w'
- Encoding:(String)默认
var fs = require('fs')
fs.writeFile('./index.txt','你好',err=>{
if(err){
console.log(err);
return;
}
console.log('创建并写入文件成功')
})
4】fs.appendFile
文件追加内容
var fs = require('fs')
fs.appendFile('./index.txt','你好',err=>{
if(err){
console.log(err);
return;
}
console.log('文件追加内容成功')
})
5】fs.readFile
读取文件内容
var fs = require('fs')
fs.readFile('./index.txt',(err,data:Buffer)=>{
if(err){
console.log(err);
return;
}
console.log('读取的内容是:',data)//默认是读取到十六进制的buffer类型
console.log(data.toString())//Buffer转成String类型
})
6】fs.readdir
读取目录(将所以的文件名或目录名存在数组中)
var fs = require('fs')
fs.readdir('./',(err,data:Array)=>{
if(err){
console.log(err);
return;
}
console.log(data)//['fliename1.html','js','filename2.css']
})
7】fs.rename
1.重命名文件或目录 2.移动文件或目录
var fs = require('fs')
fs.rename('./css/aaa.css','./css/index.css',err=>{
if(err){
console.log(err);
return;
}
console.log('文件重命名成功')
})
fs.rename('./css/aaa.css','./html/index.css',err=>{
if(err){
console.log(err);
return;
}
console.log('文件移动成功')
})
8】fs.rmdir
删除目录
var fs = require('fs')
fs.rmdir('./css',err=>{
if(err){
console.log(err);
return;
}
console.log('删除目录成功')
})
9】fs.unlink
var fs = require('fs')
fs.unlink('./css/aaa.css',err=>{
if(err){
console.log(err);
return;
}
console.log('删除文件成功')
})
四、路由
针对不同的请求的URL,处理不同的业务逻辑。
原生nodejs模块化封装接口和静态服务:
使用中间件 router[name](req, res)
的方式调用
//router.js路由配置文件
const url = require('url')
const fs = require('fs')
const app = {
//静态服务
static: (req, res, static_path) => {
const path = url.parse(req.url).pathname
path_name = path === '/' ? '/index.html' : path
if (path_name !== '/favicon.ico') {
try {
//可设置服务器的静态文件目录
const data = fs.readFileSync('./' + static_path + path_name)
if (data) {
res.end(data)
}
} catch (error) {
console.error(error)
}
}
},
login: (req, res) => {
//登录接口
res.end('login')
},
new: (req, res) => {
//新建接口
res.end('new')
},
notFound: (req, res) => {
//404接口
res.end('API 404 ERROR !!!')
}
}
module.exports = app
服务入口文件:
//index.js文件
const http = require('http');
const url = require('url')
const router = require('./router')
http.createServer((req, res) => {
router.static(req, res, 'static');
const path_name = url.parse(req.url).pathname.replace('/', '')
try {
router[path_name](req, res)
} catch (error) {
router['notFound'](req, res)
}
}).listen(8039,
() => console.log('Server running at http://localhost:8039/'))
边栏推荐
猜你喜欢
随机推荐
.equals==
【 size_t is unsigned integer (1 > 10) - > 1.
集合与函数
借问变量何处存,牧童笑称用指针,Go lang1.18入门精炼教程,由白丁入鸿儒,go lang类型指针(Pointer)的使用EP05
多线程案例——定时器
Technology Sharing | Sending Requests Using cURL
Thread,Runnable,ExecutorService线程池控制下线程量
3.List interface and implementation class
Demand side power load forecasting (Matlab code implementation)
2. Thread creation
What is the reason for the suspended animation of the migration tool in the GBase database?
主从postition变化无法锁定_Slave_IO_Running显示No_Slave_Sql_Running显示No---Mysql主从复制同步002
抛出一个问题? Mysql环境下进行Count操作执行的时候速度很慢_需手动给主键添加索引---MySql优化001
缓存击穿,缓存穿透,缓存雪崩的解释和对应的一些解决方案
【八大排序①】插入排序(直接插入排序、希尔排序)
basic operator
实用小技能:一键获取Harbor中镜像信息,快捷查询镜像
Tom Morgan | Twenty-One Rules of Life
Quick sort eight sorts (3) 】 【 (dynamic figure deduction Hoare, digging holes, front and rear pointer method)
Tom Morgan | 人生二十一条法则