node中的读取流createReadStream、写入流createWriteStream和管道流pipe
# 读取流createReadStream
const fs = require('fs')
let readStream = fs.createReadStream('./data/input.txt');
let count = 0;
let str = ""
readStream.on('data', data => {
str += data;
count++
})
readStream.on('end', () => {
console.log("count:", count)
console.log("str:", str)
})
readStream.on('error', err => {
console.log(err)
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 写入流createWriteStream
const fs = require('fs')
let str = ""
for (let i = 0; i < 500; i++){
str+='这是写入流输出的数据\n'
}
let writeStream = fs.createWriteStream('./data/output.txt');
writeStream.write(str)
writeStream.end();//只有添上这句代码,下面的finish事件才能被监听
writeStream.on('finish', () => {
console.log('写入完成')
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 管道流pipe
const fs = require('fs')
let readStream = fs.createReadStream('./data/input.txt');
let writeStream = fs.createWriteStream('./data/output.txt');
//读取input.txt文件内容,并将内容写入到output.txt文件中(原内容会被替换)
readStream.pipe(writeStream)
console.log('程序执行完毕')
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
上次更新: 2024/01/30, 00:35:17
- 01
- Node与GLIBC_2.27不兼容解决方案08-19
- 02
- Git清空本地文件跟踪缓存08-13