• 在Node.js中,使用fs模块来实现所有有关文件及目录的创建、写入及删除操作。
  • 在fs模块中,所有的方法都分为同步和异步两种实现。
  • 具有sync后缀的方法为同步方法,不具有sync后缀的方法为异步方法。

    API 风格

    fs 模块支持以标准 POSIX 函数建模的方式与文件系统进行交互。
    要使用基于 promise 的 API:
    1. import * as fs from 'fs/promises';
    要使用回调和同步的 API:
    1. import * as fs from 'fs';
    所有文件系统操作都具有同步、回调和基于 promise 的形式,并且可以使用 CommonJS 语法和 ES6 模块进行访问。 ```javascript // Promise 的示例 import { unlink } from ‘fs/promises’;

try { await unlink(‘/tmp/hello’); console.log(‘successfully deleted /tmp/hello’); } catch (error) { console.error(‘there was an error:’, error.message); }

  1. ```javascript
  2. // 回调的示例
  3. import { unlink } from 'fs';
  4. unlink('/tmp/hello', (err) => {
  5. if (err) throw err;
  6. console.log('successfully deleted /tmp/hello');
  7. });

同步方法
fs 为大部分方法提供了一个同步版本,命名规则是方法名称后面添加 xxxSync

  1. import { unlinkSync } from 'fs';
  2. try {
  3. unlinkSync('/tmp/hello');
  4. console.log('successfully deleted /tmp/hello');
  5. } catch (err) {
  6. // 处理错误
  7. }

文件读取

fs.readFile

fs.readFile(path[, options], callback) 是最常用的读取文件方法,用于异步读取文件的全部内容

  1. fs.readFile('/etc/passwd', (err, data) => {
  2. if (err) throw err;
  3. console.log(data);
  4. });
  • 回调传入了两个参数 (err, data),其中 data 是文件的内容。
  • 如果未指定编码,则返回原始缓冲区(Buffer)。

如果 options 是字符串,则它指定编码:

  1. readFile('/etc/passwd', 'utf8', callback);

同步读取:

  1. const data = fs.readFileSync(path[, options])

fs.open、fs.read、fs.close

fs.readFile 使用相当简单,在大部分读取小文件的时候我们都应该使用这个方法,但 fs.readFile() 会把文件全部内容读取,如果想精确读取部分文件内容,Node.js 也提供了类似 C 语言 fopen、fgetc、fclose 的操作

在 Node.js 中读取一个文件同样有三步

  1. fs.open(filename,flags,[mode],callback);
  2. fs.read(fd, buffer, offset, length, position, callback((err, bytesRead, buffer)))
  3. fs.write(fd, buffer[, offset[, length[, position]]], callback)

读取文件

很少使用

  1. const fs=require('fs');
  2. const path=require('path');
  3. fs.open(path.join(__dirname,'1.txt'),'r',0o666,function (err,fd) {
  4. console.log(err);
  5. let buf = Buffer.alloc(6);
  6. fs.read(fd,buf,0,6,3,function(err, bytesRead, buffer){
  7. console.log(bytesRead);//6
  8. console.log(buffer===buf);//true
  9. console.log(buf.toString());//峰培
  10. })
  11. }

写入文件

  1. const fs=require('fs');
  2. const path=require('path');
  3. fs.open(path.join(__dirname,'1.txt'),'w',0o666,function (err,fd) {
  4. console.log(err);
  5. let buf=Buffer.from('珠峰培训');
  6. fs.write(fd,buf,3,6,0,function(err, bytesWritten, buffer){
  7. console.log(bytesWritten);//6
  8. console.log(buffer===buf);//true
  9. console.log(buf.toString());//珠峰培训
  10. })
  11. })

文件写入

fs.writeFile

写入的时候默认讲内容以 UTF-8 格式写入
fs.writeFile(file, data[, options], callback)

  1. file:文件名或文件描述符
  2. data:常用的主要是 string 和 buffer
  3. options
    • encoding
    • flag flag 默认 = ‘w’
    • mode 读写权限,默认为0666
  4. callback(err)

file 是文件名时,则异步地写入数据到文件,如果文件已存在,则覆盖文件内容

  1. import { writeFile } from 'fs';
  2. import { Buffer } from 'buffer';
  3. const data = new Uint8Array(Buffer.from('Hello Node.js'));
  4. writeFile('message.txt', data, (err) => {
  5. if (err) throw err;
  6. console.log('The file has been saved!');
  7. });

同步写入:

  1. fs.writeFileSync(file, data[, options])

fs.appendFile

fs.write

fs.write 有两种重载

  1. fs.write(fd, buffer[, offset[, length[, position]]], callback):参数含义和 fs.read 几乎相同
  2. fs.write(fd, string[, position[, encoding]], callback):只能把字符串内容全部写入文件

两个的区别就是使用 buffer 可以只写入 buffer 中 offset ~ length + offset 的内容,而使用字符串只能把字符串内容全部写入文件