- 在Node.js中,使用fs模块来实现所有有关文件及目录的创建、写入及删除操作。
- 在fs模块中,所有的方法都分为同步和异步两种实现。
- 具有sync后缀的方法为同步方法,不具有sync后缀的方法为异步方法。
API 风格
fs 模块支持以标准 POSIX 函数建模的方式与文件系统进行交互。
要使用基于 promise 的 API:
要使用回调和同步的 API:import * as fs from 'fs/promises';
所有文件系统操作都具有同步、回调和基于 promise 的形式,并且可以使用 CommonJS 语法和 ES6 模块进行访问。 ```javascript // Promise 的示例 import { unlink } from ‘fs/promises’;import * as fs from 'fs';
try { await unlink(‘/tmp/hello’); console.log(‘successfully deleted /tmp/hello’); } catch (error) { console.error(‘there was an error:’, error.message); }
```javascript
// 回调的示例
import { unlink } from 'fs';
unlink('/tmp/hello', (err) => {
if (err) throw err;
console.log('successfully deleted /tmp/hello');
});
同步方法
fs 为大部分方法提供了一个同步版本,命名规则是方法名称后面添加 xxxSync
import { unlinkSync } from 'fs';
try {
unlinkSync('/tmp/hello');
console.log('successfully deleted /tmp/hello');
} catch (err) {
// 处理错误
}
文件读取
fs.readFile
fs.readFile(path[, options], callback)
是最常用的读取文件方法,用于异步读取文件的全部内容
fs.readFile('/etc/passwd', (err, data) => {
if (err) throw err;
console.log(data);
});
- 回调传入了两个参数 (err, data),其中 data 是文件的内容。
- 如果未指定编码,则返回原始缓冲区(Buffer)。
如果 options 是字符串,则它指定编码:
readFile('/etc/passwd', 'utf8', callback);
同步读取:
const data = fs.readFileSync(path[, options])
fs.open、fs.read、fs.close
fs.readFile 使用相当简单,在大部分读取小文件的时候我们都应该使用这个方法,但 fs.readFile() 会把文件全部内容读取,如果想精确读取部分文件内容,Node.js 也提供了类似 C 语言 fopen、fgetc、fclose 的操作
在 Node.js 中读取一个文件同样有三步
fs.open(filename,flags,[mode],callback);
fs.read(fd, buffer, offset, length, position, callback((err, bytesRead, buffer)))
fs.write(fd, buffer[, offset[, length[, position]]], callback)
读取文件
很少使用
const fs=require('fs');
const path=require('path');
fs.open(path.join(__dirname,'1.txt'),'r',0o666,function (err,fd) {
console.log(err);
let buf = Buffer.alloc(6);
fs.read(fd,buf,0,6,3,function(err, bytesRead, buffer){
console.log(bytesRead);//6
console.log(buffer===buf);//true
console.log(buf.toString());//峰培
})
}
写入文件
const fs=require('fs');
const path=require('path');
fs.open(path.join(__dirname,'1.txt'),'w',0o666,function (err,fd) {
console.log(err);
let buf=Buffer.from('珠峰培训');
fs.write(fd,buf,3,6,0,function(err, bytesWritten, buffer){
console.log(bytesWritten);//6
console.log(buffer===buf);//true
console.log(buf.toString());//珠峰培训
})
})
文件写入
fs.writeFile
写入的时候默认讲内容以 UTF-8 格式写入fs.writeFile(file, data[, options], callback)
- file:文件名或文件描述符
- data:常用的主要是 string 和 buffer
- options
- encoding
- flag flag 默认 = ‘w’
- mode 读写权限,默认为0666
- callback(err)
当 file
是文件名时,则异步地写入数据到文件,如果文件已存在,则覆盖文件内容
import { writeFile } from 'fs';
import { Buffer } from 'buffer';
const data = new Uint8Array(Buffer.from('Hello Node.js'));
writeFile('message.txt', data, (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
同步写入:
fs.writeFileSync(file, data[, options])
fs.appendFile
fs.write
fs.write 有两种重载
- fs.write(fd, buffer[, offset[, length[, position]]], callback):参数含义和 fs.read 几乎相同
- fs.write(fd, string[, position[, encoding]], callback):只能把字符串内容全部写入文件
两个的区别就是使用 buffer 可以只写入 buffer 中 offset ~ length + offset
的内容,而使用字符串只能把字符串内容全部写入文件