更新于 

文件写入

fs文件系统

File System
  • Node中,与文件系统交互非常重要,
    • 服务端的本质就是将本地文件发给远程客户端。
    • 文件系统简单说就是使用node对系统中文件进行操作
  • Node通过fs模块和文件系统进行交互
  • fs模块提供了一些标准文件访问API来打开、读取、写入文件,以及与其交互
  • 要使用fs模块,需要先对其进行加载:
    • const fs = require(“fs”);

同步和异步调用

fs模块所有操作都有两种形式可供选择:

  • 同步fs
    • 会阻塞程序执行
  • 异步fs
    • 不会阻塞程序执行
    • 通过callback回调函数返回结果

同步文件写入

完整步骤

1
2
3
4
5
6
7
8
const fs = require('fs');
// 1. 打开文件
let result = fs.openSync('hello.txt', 'w');
console.log(result); //3
// 2. 写入文件
fs.writeSync(result, 'Hello world!')
// 3. 关闭文件
fs.closeSync(result);
openSync

步骤1 打开文件

1
fs.openSync(path, flags[, mode])
  • path 要打开文件的路径
  • flags 打开文件要做的操作类型
    • r 只读
    • w 可写
  • mode 设置文件的操作权限,一般不传

返回值

  • 该方法会返回一个文件的描述符作为结果,
    可以通过该描述符对文件进行各种操作

步骤2 向文件中写入内容

1
fs.wraiteSync(fd, string[, position[, encoding]])
  • fd 文件的描述符,需要传递要写入的文件的描述符
  • string 要写入的内容
  • position 写入的起始位置,默认是0,一般不传
  • encoding 编码格式,默认是UTF-8,一般不传

步骤3 保存并关闭文件

1
fs.closeSync(fd)
  • fd 要关闭文件的描述符
writeSync的position参数

不传position,默认为0

1
fs.syncWrite( file, "Hello World!");

运行结果

指定position,相当于在指定偏移位置进行写入操作

1
fs.syncWrite( file, "Hello World!" ,20);

运行结果

异步文件写入

write
open(path, flags[, mode], callback)

异步调用的方法结果都是通过回调函数callback的参数返回的,

1
2
3
fs.open('hello.txt', 'w', function () {
console.log(arguments);
})

[Arguments] { ‘0’: null, ‘1’: 3 }

这里callback的两个参数:

  • err 错误对象,如果没有错误则为null
  • fd 文件的描述符

完整流程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const fs = require('fs');
// 1 打开文件
fs.open('hello.txt', 'w', function (err, fd) {
if (!err) {
console.log(fd);
// 2 写入文件
fs.write(fd, "Hello World!", function (err) {
if (!err) {
// 3 关闭文件
fs.close(fd, function (err) {
if (!err) {
console.log('file closed')
}
});
}
});
} else {
console.log(err);
}
})

简单文件写入

同步-简单文件写入
1
fs.writeFile(file, data[, options], callback)
  • file 要操作文件路径
  • data 要写入的数据
  • options 选项,Object/String,可以对写入进行一些设置
    • encoding
    • mode
    • flag 默认w
  • callback 当写入完成以后执行的函数

完整流程

1
2
3
4
5
6
7
8
9
10
const fs = require('fs');
fs.writeFile(
"hello.txt",
'wraiteFile_Hello!',
function (err) {
if (!err) {
console.log('write success');
}
}
);
异步-简单文件写入
1
fs.writeFileSync(file, data[, options])

流式文件写入

同步、异步、简单文件写入都不适合 大文件 写入,
性能较差,容易导致内存溢出.

fs.createWriteStream(path[, options])

该方法可以用来创建一个可写流

  • path 文件路径
  • options 配置参数
监听流

可以通过open和close事件来监听流的打开和关闭,
因为ws的打开和关闭是一次性事件,因此用once绑定更好

1
2
3
4
5
6
ws.once("open", function () { 
console.log("Stream Open");
})
ws.once("close", function () {
console.log("Stream close")
})

完整流程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const fs = require('fs');
//创建一个可写流
let ws = fs.createWriteStream('hello.txt');
// 通过可写流向文件输出内容
ws.write('stream_write\n');
ws.write('1 Hello!!!\n');
ws.write('2 Hello!!!\n');
ws.write('3 Hello!!!\n');

ws.once("open", function () {
console.log("Stream Open");
})
ws.once("close", function () {
console.log("Stream close")
})
ws.end();