课程名称: 新版 Node.js+Express+Koa2 开发Web Server博客
课程章节: 8-5 stream演示(2)
课程讲师: 双越
课程内容:
文件io stream:
当前目录:
- 创建 data.txt ,要拷贝的文件,需要有内容
- 创建 data-bak.txt,拷贝后数据存放文件
// 复制文件
const fs = require("fs");
const path = require("path");
const fileName1 = path.resolve(__dirname, "data.txt");
const fileName2 = path.resolve(__dirname, "data-bak.txt");
// 读取文件的流
const readStream = fs.createReadStream(fileName1);
// 写入文件的流
const writeStream = fs.createWriteStream(fileName2);
readStream.pipe(writeStream);
// 监听流读取的内容
readStream.on("data", (chunk) => {
console.log(chunk.toString());
});
// 监听了流读取完成
readStream.on("end", () => {
console.log("copy done");
});
结合文件io和网络io的strmea:
const http = require("http");
const fs = require("fs");
const path = require("path");
const fileName1 = path.resolve(__dirname, "data.txt");
const server = http.createServer((req, res) => {
if (req.method === "GET") {
// 读取文件的流
const readStream = fs.createReadStream(fileName1);
readStream.pipe(res);
}
});
server.listen(8004);
课程收获:
- 了解文件和网络的io怎么操作