"使用 TypeScript 编写一个类及其配置,用于异步文件操作:"\n"\ntypescript\nimport * as fs from \'fs\';\n\nclass FileHandler {\n private filePath: string;\n\n constructor(filePath: string) {\n this.filePath = filePath;\n }\n\n async readLine(lineNumber: number): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n const readStream = fs.createReadStream(this.filePath, { encoding: \'utf8\' });\n let currentLine = 0;\n let lineData = \'\';\n\n readStream.on(\'data\', (chunk: string) => {\n for (let i = 0; i < chunk.length; i++) {\n if (chunk[i] === \'\n\') {\n currentLine++;\n if (currentLine === lineNumber) {\n resolve(lineData);\n readStream.close();\n return;\n }\n lineData = \'\';\n } else {\n lineData += chunk[i];\n }\n }\n });\n\n readStream.on(\'end\', () => {\n reject(new Error(\'Line number exceeds total line count.\'));\n });\n });\n }\n}\n\nexport default FileHandler;\n\n"使用示例:"\n"typescript\nconst fileHandler = new FileHandler(\'path/to/file.txt\');\n\nfileHandler.readLine(4)\n .then((line: string) => {\n console.log(line);\n })\n .catch((error: Error) => {\n console.error(error.message);\n });\n\n"注意:以上代码仅支持读取 UTF-8 编码的文本文件,并且每行以换行符分隔。"


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

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