1.Buffer对象(不需要引入)
Bufferd对象用途:
以二进制流进行数据的传送传递
1.三种创建方式(类似于数组的创建,用16进制存储)
let buf1 = Buffer.alloc(20, 13);
console.log(buf1);
<Buffer 0d 0d 0d 0d 0d 0d 0d 0d 0d 0d 0d 0d 0d 0d 0d 0d 0d 0d 0d 0d>
2.不确定大小,内部可能有脏数据
let buf2 = Buffer.allocUnsafe(10, 0)
console.log(buf2);
<Buffer 00 00 00 00 00 00 00 00 00 00>
3.转换为二进制
let arr = [1, 2, 3];
let buf4 = Buffer.from(arr);
console.log(buf4); //<Buffer 01 02 03>
4.常用
let buf5 = Buffer.from('hello,world');
console.log(buf5);//<Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
console.log(buf5.toString());hello world
常用方法一:填充fill()
buf5.fill(0, 3);
console.log(buf5);<Buffer 68 65 6c 00 00 00 00 00 00 00 00>
console.log(buf5.toString());hel
常用方法二:write()写入内容
buf5.write("ni", 0, 3, 'utf-8');
buf5.write("hao", 2, 3, 'utf-8');
console.log(buf5.toString());
常用方法三:isBuffer() 判断是否是二进制流
let buf7 = Buffer.alloc(5);
console.log(Buffer.isBuffer(buf7)); //true
console.log(Buffer.isBuffer([])); //false
常用方法四:.length
console.log(buf7.length); // 5
常用方法5:.bytelength
console.log(buf7.byteLength); // 5
2.fs模块
2.1 同步和异步读取
// 1.引入文件系统
const fs = require('fs');
// 2.同步读取文件
let fd = fs.readFileSync(__dirname + '/read/test.txt')
console.log(fd.toString()); //hello,nodejs
console.log("后续的操作");
// 3.异步读取文件,不会等待后续操作
fs.readFile(__dirname + '/read/test.txt', (err, data) => {
if (err) {
console.log(err);
} else {
console.log(data.toString());
}
})
console.log("后续的操作");
2.2 同步写入
const fs = require('fs');
// 1.打开文件
let fd = fs.openSync(__dirname + '/read/b.txt', 'w+')
console.log(fd);
// 2.同步写入文件
fs.writeFileSync(fd, "陕西西安",)
// 3.保存并退出
fs.closeSync(fd);
// 4.后续操作
console.log("后续的操作");
2.3异步写入
const fs = require('fs');
// 1.打开文件
fs.open(__dirname + '/read/b.txt', 'w+', (err, fd) => {
if (!err) {
// 2.写入文件
fs.writeFile(fd, `张三${Date.now()}`, (err) => {
if (!err) {
console.log("写入文件成功");
} else {
throw err;
}
})
// 3.文件
fs.close(fd, (err) => {
if (!err) {
console.log("文件已经保存并关闭");
} else {
throw err;
}
})
}
})
console.log("后续操作");
2.4copy实现
const fs = require('fs');
copy('', '', (err) => {
})
// fs.copyFile()
let copy = (src, target, callBack) => {
// 1.读文件
fs.readFile(src, (err, data) => {
if (!err) {
// 2.写文件
fs.writeFile(target, data, (err, data) => {
if (!err) {
callBack && callBack(err, data)
} else {
throw err;
}
})
}
})
}
copy(__dirname + '/read/b.txt', __dirname + '/read/d.txt', (err) => {
if (!err) {
console.log("文件拷贝成功");
}
})
2.5 读入流和写入流
// 1.创建读写流
const fs = require('fs')
const rs = fs.createReadStream("C:/Users/86136/Music/CloudMusic/许嵩 - 清明雨上.mp3")
const ws = fs.createWriteStream(__dirname + '/read/hello.mp3')
// 2.监听流的打开
rs.once('open', () => {
console.log("写入流打开------");
})
// 2.监听流的读入
ws.once('open', () => {
console.log("读入流打开------");
})
// 3.监听data
rs.on('data', (data) => {
console.log(data);
ws.write(data);
})
// 4.监听流的关闭
rs.once('end', () => {
console.log("读入数据已经完成");
})
rs.once('close', () => {
console.log("读入通道已经关闭");
})
2.6 pipe管道
// 1.创建读写流
const fs = require('fs')
const rs = fs.createReadStream("C:/Users/86136/Music/CloudMusic/许嵩 - 清明雨上.mp3")
const ws = fs.createWriteStream(__dirname + '/read/hello999.mp3')
// 2.创建管道
rs.pipe(ws);
pipe实现
rs.on('data', (data) => {
let flag = ws.write(data)
console.log(flag); // 下面的操作没有完成,都会返回false
if (!flag) {
// 暂停操作
rs.pause()
}
})
ws.on('drain', () => {
// 继续读取流
rs.resume()
})
rs.read('end', () => {
ws.end()
})
3.http模块
创建httpServer
const http = require('http');
let server = http.createServer((req, res) => {
res.end("hello,nodejs");
})
server.listen(8888, "127.0.0.1", () => {
console.log("server running at http://127.0.0.1:8888");
// 6s后关闭服务器
/* setTimeout(() => {
server.close();
}, 6000); */
});
// 1.监听服务器关闭
server.on('close', () => {
console.log("服务器已经关闭");
})
// 2.监听服务器发生错误
server.on('error', (e) => {
if (e.code === "EADDRINUSE") {
console.log("端口号被调用");
} else {
console.log("其他错误");
}
})
// 3.设置超时时间
server.setTimeout(1000, () => {
console.log("设置超时时间为1s");
})
server.on('timeout', () => {
// 超时要做什么操作
console.log("连接已经超时");
})
4.URL模块
==把字符串转成url对象 ==
const url = require('url');
// url.parse()不推荐
const myURL = new URL("https://editor.csdn.net/md/?articleId=121215760");
console.log(myURL);
5.请求数据接收实例
<form action="http://127.0.0.1:8888" method="POST">
<label for=" ">用户名: <input type="text" name="userName"></label>
<label for="">密码: <input type="text" name="userPsw"></label>
<input type="submit" value="提交">
</form>
const http = require('http');
const queryString = require('querystring');
const util = require('util');
const server = http.createServer((req, res) => {
console.log(req.method);
res.writeHead(200, {
"Content-Type": 'text/plain',
'charset': 'utf-8',
'Access-Control-Allow-Origin': '*',
// 可以解决跨域请求
'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS'
});
// post请求得做事件监听
let postData = '';
req.on('data', (data) => {
postData += data
})
// 监听数据接收完毕
req.on('end', () => {
postData = queryString.parse(postData)
console.log(postData);
})
res.end("success")
})
server.listen(8888, () => {
console.log("服务已经启动");
})
6.web容器搭建
对不同页面进行数据响应
const http = require('http');
const url = require('url')
const fs = require('fs');
const path = require('path')
const server = http.createServer((req, res) => {
let pathUrl = url.parse(req.url)
let pathName = pathUrl.pathname
// console.log(pathName);
// 要加载什么资源,要在请求头里添加Content-Type
if (pathName === '/page1') {
fs.readFile(path.join(__dirname + '/static/page1.html'), (err, data) => {
if (!err) {
res.writeHead(200, {
"Content-Type": 'text/html',
'charset': 'utf-8',
})
res.end(data)
} else {
throw err;
}
})
} else if (pathName === '/page2') {
fs.readFile(path.join(__dirname + '/static/page2.html'), (err, data) => {
if (!err) {
res.writeHead(200, {
"Content-Type": 'text/html',
'charset': 'utf-8',
})
res.end(data)
} else {
throw err;
}
})
} else if (pathName === '/css') {
fs.readFile(path.join(__dirname + '/static/index.css'), (err, data) => {
if (!err) {
res.writeHead(200, {
"Content-Type": 'text/css',
'charset': 'utf-8',
})
res.end(data)
} else {
throw err;
}
})
} else if (pathName === '/img1') {
fs.readFile(path.join(__dirname + '/static/img1.jpg'), (err, data) => {
if (!err) {
res.writeHead(200, {
"Content-Type": 'text/plain',
'charset': 'utf-8',
})
res.end(data)
} else {
throw err;
}
})
} else {
res.writeHead(404, {
"Content-Type": 'text/html',
'charset': 'utf-8',
})
res.end("<h1>404...</h1>")
}
})
server.listen(8888)
————————————————
版权声明:本文为CSDN博主「Melody_kui」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/m0_51279688/article/details/121215760
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)