Skip to content

Commit

Permalink
feat: add readJsonFile/writeJsonFile/trimChars func
Browse files Browse the repository at this point in the history
  • Loading branch information
zhangfisher committed Feb 26, 2025
1 parent 48751bf commit e698bb3
Show file tree
Hide file tree
Showing 8 changed files with 160 additions and 6 deletions.
33 changes: 33 additions & 0 deletions docs/guide/fs.md
Original file line number Diff line number Diff line change
Expand Up @@ -304,3 +304,36 @@ import {mkdir,writeFile,readFile} from 'flex-tools/fs/nodefs'
await mkdir('d:/temp/a/b/c',{recursive:true}) // 创建文件夹
```

## writeJsonFile

更新json文件

```typescript
writeJsonFile("d:/temp/package.json",{
name:"myapp",
version:"1.0.0"
})
```

- 如果文件不存在,则会创建文件。
- 如果目标文件存在,则会深度合并对象。

## writeJsonFileAsync

writeJsonFile的异步版本


## readJsonFile

读取json文件

```
readJsonFile(jsonfile: string,defaultValue?:Record<string,any>)
```
- 如果文件不存在,则返回`defaultValue`参数。
- 如果文件存在且提供`defaultValue`参数,则会深度合并对象。
## readJsonFileAsync
readJsonFile的异步版本
13 changes: 12 additions & 1 deletion docs/guide/string.md
Original file line number Diff line number Diff line change
Expand Up @@ -499,4 +499,15 @@ test("Matcher",() => {
expect(matcher.test("myapp/src/test/ss.ts")).toBe(false)
expect(matcher.test("myapp/src/test/ss.js")).toBe(true)
})
```
```


## trimChars

去掉字符串前后的指定字符

```typescript
"<[abc123xyz]>".trimChars("abc","<>[]") // == "123xyz"
"'abc123xyz'".trimChars("xyz") // == "abc123"
```

18 changes: 14 additions & 4 deletions src/fs/copyFiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,15 @@ export interface CopyFilesOptions {
error? : (error:Error,{source,target}:{source: string, target: string})=>void | typeof ABORT // 复制出错的回调
templateOptions?: Record<string, any> | ((file: string) => Record<string, any> | Promise<Record<string, any>>);
}

export async function copyFiles( pattern: string, targetDir: string, options?: CopyFilesOptions) {
/**
* 拷贝满足条件的文件到目标文件夹
*
* @param pattern
* @param targetDir
* @param options
* @returns 返回实际拷贝的文件列表
*/
export async function copyFiles( pattern: string, targetDir: string, options?: CopyFilesOptions):Promise<string[]> {

const opts = assignObject({
ignore : [],
Expand All @@ -62,8 +69,10 @@ export async function copyFiles( pattern: string, targetDir: string, options?: C
if (opts.clean) {
try{await cleanDir(targetDir)}catch{}
}

const copyedFiles:string[] = []

return new Promise<void>((resolve, reject) => {
return new Promise<string[]>((resolve, reject) => {
glob(pattern, {
ignore,
cwd:srcDir,
Expand Down Expand Up @@ -92,6 +101,7 @@ export async function copyFiles( pattern: string, targetDir: string, options?: C
}
try {
await copyFile(fromFile, toFile, opts);
copyedFiles.push(toFile)
if (typeof options?.after == "function") {
if(options.after(fileInfo)===ABORT){
break
Expand All @@ -105,7 +115,7 @@ export async function copyFiles( pattern: string, targetDir: string, options?: C
}
}
}
resolve();
resolve(copyedFiles);
}).catch(reject);
});
}
13 changes: 13 additions & 0 deletions src/fs/fileIsExists.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,17 @@ export function fileIsExists(filename:string):boolean{
}catch{
return false
}
}

/**
* 异步检查文件是否存在
* @param filename
*/
export async function fileIsExistsAsync(filename: string): Promise<boolean> {
try {
await fs.promises.stat(filename);
return true;
} catch {
return false;
}
}
4 changes: 3 additions & 1 deletion src/fs/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,6 @@ export * from "./getExistedDir"
export * from "./fileIsExists"
export * from "./copyFiles"
export * from "./copyDirs"
export * from "./copyFile"
export * from "./copyFile"
export * from "./writeJsonFile"
export * from "./readJsonFile"
26 changes: 26 additions & 0 deletions src/fs/readJsonFile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@

import fs from 'node:fs'
import { deepMerge } from '../object/deepMerge';
import { promises as fsPromises } from 'node:fs';

export function readJsonFile(jsonfile: string,defaultValue?:Record<string,any>) {
let json = {}
if(fs.existsSync(jsonfile)){
json = JSON.parse(fs.readFileSync(jsonfile,{encoding:'utf-8'}).toString())
}
if(defaultValue){
json = deepMerge({},defaultValue,json)
}
return json
}

export async function readJsonFileAsync(jsonfile: string, defaultValue?: Record<string, any>) {
let json = {};
if (await fsPromises.access(jsonfile).then(() => true).catch(() => false)) {
json = JSON.parse((await fsPromises.readFile(jsonfile, { encoding: 'utf-8' })).toString());
}
if (defaultValue) {
json = deepMerge({}, defaultValue, json);
}
return json;
}
26 changes: 26 additions & 0 deletions src/fs/writeJsonFile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@

import fs from 'node:fs';
import { deepMerge } from '../object/deepMerge';
import { promises as fsPromises } from 'node:fs';

export function writeJsonFile(jsonfile: string, data:Record<string,any>) {
let json = {}
if(fs.existsSync(jsonfile)){
json = JSON.parse(fs.readFileSync(jsonfile,{encoding:'utf-8'}).toString())
}
json = deepMerge(json,data)
fs.writeFileSync(jsonfile,JSON.stringify(json,null,4))
return json

}

export async function writeJsonFileAsync(jsonfile: string, data: Record<string, any>) {
let json = {};
if (await fsPromises.stat(jsonfile).then(() => true).catch(() => false)) {
const fileContent = await fsPromises.readFile(jsonfile, { encoding: 'utf-8' });
json = JSON.parse(fileContent.toString());
}
json = deepMerge(json, data);
await fsPromises.writeFile(jsonfile, JSON.stringify(json, null, 4));
return json;
}
33 changes: 33 additions & 0 deletions src/string/trimChars.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@

/**
* 移除字符串前后的字符
*
* trimChars(" hello world ") => "hello world"
* trimChars(" \nhello world\n ") => "hello world"
*
* @param {*} str
* @param {*} chars
* @returns
*/
export function trimChars(str:string,chars:string=`"'`){
let start = 0
let end = str.length
const arrChars = chars.split('')
while(start<end && arrChars.includes(str[start])){
start++
}
while(end>start && arrChars.includes(str[end-1])){
end--
}
return str.substring(start,end)
}

String.prototype.trimChars=function(this:string,chars:string){
return trimChars(this,chars)
}

declare global {
interface String {
trimChars(chars: string): string
}
}

0 comments on commit e698bb3

Please sign in to comment.