使用 TypeScript 编写的文件操作类及其配置,用于处理文件相关操作。

import * as fs from 'fs';

class FileHandler {
  private filePath: string;

  constructor(filePath: string) {
    this.filePath = filePath;
  }

  public async turnTo(lineNumber: number): Promise<string | null> {
    try {
      const lines = await this.readFileLines();
      if (lineNumber < 1 || lineNumber > lines.length) {
        throw new Error('Invalid line number');
      }
      return lines[lineNumber - 1];
    } catch (error) {
      console.error(error);
      return null;
    }
  }

  public async readLine(): Promise<string | null> {
    try {
      const lines = await this.readFileLines();
      if (lines.length === 0) {
        return null;
      }
      const line = lines.shift();
      await this.writeFileLines(lines);
      return line;
    } catch (error) {
      console.error(error);
      return null;
    }
  }

  private async readFileLines(): Promise<string[]> {
    return new Promise<string[]>((resolve, reject) => {
      fs.readFile(this.filePath, 'utf-8', (error, data) => {
        if (error) {
          reject(error);
        } else {
          const lines = data.split('\n');
          resolve(lines);
        }
      });
    });
  }

  private async writeFileLines(lines: string[]): Promise<void> {
    return new Promise<void>((resolve, reject) => {
      fs.writeFile(this.filePath, lines.join('\n'), 'utf-8', (error) => {
        if (error) {
          reject(error);
        } else {
          resolve();
        }
      });
    });
  }
}

// Example usage
const fileHandler = new FileHandler('example.txt');

fileHandler.turnTo(3)
  .then((line) => console.log(line))
  .catch((error) => console.error(error));

fileHandler.readLine()
  .then((line) => console.log(line))
  .catch((error) => console.error(error));

该类包含以下功能:

  • constructor 用于接受文件的相对路径。
  • turnTo 方法用于根据指定的行号返回文件中对应行的内容。
  • readLine 方法用于一行一行地读取文件。
  • readFileLines 方法使用 fs.readFile 异步函数读取文件内容。
  • writeFileLines 方法使用 fs.writeFile 异步函数将行数组的内容写入文件。

示例代码演示了如何使用该类进行文件操作。


原文地址: https://www.cveoy.top/t/topic/pRmi 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录