NodeJs中fs模块提供了readFile和readFileSync方法,为什么还要使用文件流呢?
其实文件流的优势:
1.边读,边写。占用内存比较少,不必一次性把文件内容全部读取到内存中。
以下代码实现了,将文件hello.txt拷贝到hello3.txt的功能
const fs = require('fs')
let count = 0
const inStream = fs.createReadStream('./hello.txt', {
flags: 'r',
encoding: 'utf-8',
highWaterMark: 5
})
const outStream = fs.createWriteStream('./hello3.txt', {
flags: 'w',
encoding: 'utf-8',
highWaterMark: 1
})
inStream.pipe(outStream)
// inStream.on('data', (chunk) => {
// count += chunk.length
// if(outStream.write(chunk) == false) {
// inStream.pause()
// }
// })
// inStream.on('end', () => {
// console.log('read file completed.' + count)
// })
// outStream.on('drain', () => {
// inStream.resume()
// })
网友评论