本篇文章将介绍nodejs中stream文件流相关操作。
文件拷贝
const fs = require('fs')
const path = require('path')
// 文件路径
const filename = path.resolve(__dirname, 'data.txt')
const backFile = path.resolve(__dirname, 'back.txt')
// 创建读取流
const readStream = fs.createReadStream(filename)
// 创建写入流
const writeStream = fs.createWriteStream(backFile)
// 执行拷贝:pipe(不是一次性拷贝,而是一点点写入)
readStream.pipe(writeStream)
// 监听数据拷贝状态
readStream.on('end', () => {
console.log('拷贝完成')
})
读写网络日志
将每次访问的GET请求日志写入到文件。
const fs = require('fs')
const path = require('path')
const http = require('http')
const logFile = path.resolve(__dirname,'data.txt')
// 创建server
const server = http.createServer((req, res) => {
const method = req.method
if (method === 'GET') {
const readStream= fs.createReadStream(logFile)
// 将本地文件内容写入到res中去
readStream.pipe(res)
}
})
// 监听端口
server.listen(8000, () => {
console.log('监听端口8000的GET请求...')
})