From ba70d4363cf02d3b8d91c47d5f84c653d52d0a4f Mon Sep 17 00:00:00 2001 From: hello8693 <1320998105@qq.com> Date: Fri, 21 Mar 2025 20:47:50 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E6=96=87=E4=BB=B6=E5=B7=A5?= =?UTF-8?q?=E5=85=B7=E5=87=BD=E6=95=B0=EF=BC=8C=E6=8F=90=E4=BE=9B=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E8=AF=BB=E5=86=99=E3=80=81=E7=9B=AE=E5=BD=95=E5=88=9B?= =?UTF-8?q?=E5=BB=BA=E5=92=8C=E6=96=87=E4=BB=B6=E5=88=A0=E9=99=A4=E5=8A=9F?= =?UTF-8?q?=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/fileUtils.ts | 79 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 src/main/fileUtils.ts diff --git a/src/main/fileUtils.ts b/src/main/fileUtils.ts new file mode 100644 index 0000000..5421db5 --- /dev/null +++ b/src/main/fileUtils.ts @@ -0,0 +1,79 @@ +import * as fs from 'fs'; +import * as path from 'path'; + +export const readFile = (filePath: string): Promise => { + return new Promise((resolve, reject) => { + fs.readFile(filePath, 'utf8', (err, data) => { + if (err) { + reject(err); + } else { + resolve(data); + } + }); + }); +}; + +export const writeFile = (filePath: string, content: string): Promise => { + return new Promise((resolve, reject) => { + fs.writeFile(filePath, content, 'utf8', (err) => { + if (err) { + reject(err); + } else { + resolve(); + } + }); + }); +}; + +export const readJSONFile = async (filePath: string): Promise => { + const content = await readFile(filePath); + return JSON.parse(content); +}; + +export const writeJSONFile = (filePath: string, jsonData: any): Promise => { + const content = JSON.stringify(jsonData, null, 2); + return writeFile(filePath, content); +}; + +export const fileExists = (filePath: string): Promise => { + return new Promise((resolve) => { + fs.access(filePath, fs.constants.F_OK, (err) => { + resolve(!err); + }); + }); +}; + +export const createDirectory = (dirPath: string): Promise => { + return new Promise((resolve, reject) => { + fs.mkdir(dirPath, { recursive: true }, (err) => { + if (err) { + reject(err); + } else { + resolve(); + } + }); + }); +}; + +export const deleteFile = (filePath: string): Promise => { + return new Promise((resolve, reject) => { + fs.unlink(filePath, (err) => { + if (err) { + reject(err); + } else { + resolve(); + } + }); + }); +}; + + +export const fileApi = { + readFile: (filePath: string) => readFile(filePath), + writeFile: (filePath: string, content: string) => writeFile(filePath, content), + readJSONFile: (filePath: string) => readJSONFile(filePath), + writeJSONFile: (filePath: string, jsonData: any) => writeJSONFile(filePath, jsonData), + fileExists: (filePath: string) => fileExists(filePath), + createDirectory: (dirPath: string) => createDirectory(dirPath), + deleteFile: (filePath: string) => deleteFile(filePath) +}