"使用 TypeScript 编写的文件操作类及其配置,其中构造函数接受一个相对路径:\n\ntypescript\nimport * as fs from 'fs';\\n\ninterface FileOptions {\n encoding?: string;\n flag?: string;\n}\n\nclass File {\n private path: string;\n private options: FileOptions;\n\n constructor(path: string, options: FileOptions = {}) {\n this.path = path;\n this.options = options;\n }\n\n read(): string {\n const fileData = fs.readFileSync(this.path, this.options);\n return fileData.toString();\n }\n\n write(data: string): void {\n fs.writeFileSync(this.path, data, this.options);\n }\n\n append(data: string): void {\n fs.appendFileSync(this.path, data, this.options);\n }\n\n delete(): void {\n fs.unlinkSync(this.path);\n }\n}\n\n// Example usage\nconst filePath = './example.txt'; // Relative path to the file\\n\nconst file = new File(filePath, { encoding: 'utf8' });\\n\n// Read file\nconst fileContent = file.read();\nconsole.log(fileContent);\\n\n// Write to file\nfile.write('Hello, World!');\\n\n// Append to file\nfile.append(' This is an appended text.');\\n\n// Read file again\nconst updatedContent = file.read();\nconsole.log(updatedContent);\\n\n// Delete file\nfile.delete();\n\n\n这个类提供了读取、写入、追加和删除文件的功能。您可以通过创建一个 File 对象并传递文件的相对路径来使用这些功能。可以通过调用 read 方法来读取文件内容,通过调用 write 方法来覆盖文件内容,通过调用 append 方法来追加内容到文件末尾,通过调用 delete 方法来删除文件。


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

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