更新于 

文件读取

简单文件读取

  • readFile(path[, options], callback)
    • callback参数
      • err 错误
      • data Buffer类型
  • readFileSync(path[, options])

完整流程

1
2
3
4
5
6
7
8
9
10
11
const fs = require('fs');
fs.readFile('hello.txt', function (err, data) {
if (!err) {
console.log(data.toString());
fs.writeFile('hello_copy.txt', data, function (err) {
if (!err) {
console.log('copy success')
}
})
}
})

流式文件读取

如果要读取一个可读流中的数据,
必须要为可读流绑定一个data事件,
data事件绑定完毕,就会自动开始读取数据

1
2
3
rs.on('data', function (data) {
console.log(data + "");
})

使用pipe快速copy流式文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
let fs = require('fs');

let rs = fs.createReadStream('hello.txt');
let ws = fs.createWriteStream('hello_copy_stream.txt');

rs.once('open', function () {
console.log('rs open');
})

rs.once('close', function () {
console.log('rs close');
})

ws.once('open', function () {
console.log('ws open');
})

ws.once('close', function () {
console.log('ws close');
})

rs.pipe(ws);