Skip to content

Commit e698bb3

Browse files
committed
feat: add readJsonFile/writeJsonFile/trimChars func
1 parent 48751bf commit e698bb3

File tree

8 files changed

+160
-6
lines changed

8 files changed

+160
-6
lines changed

docs/guide/fs.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -304,3 +304,36 @@ import {mkdir,writeFile,readFile} from 'flex-tools/fs/nodefs'
304304
await mkdir('d:/temp/a/b/c',{recursive:true}) // 创建文件夹
305305
306306
```
307+
308+
## writeJsonFile
309+
310+
更新json文件
311+
312+
```typescript
313+
writeJsonFile("d:/temp/package.json",{
314+
name:"myapp",
315+
version:"1.0.0"
316+
})
317+
```
318+
319+
- 如果文件不存在,则会创建文件。
320+
- 如果目标文件存在,则会深度合并对象。
321+
322+
## writeJsonFileAsync
323+
324+
writeJsonFile的异步版本
325+
326+
327+
## readJsonFile
328+
329+
读取json文件
330+
331+
```
332+
readJsonFile(jsonfile: string,defaultValue?:Record<string,any>)
333+
```
334+
- 如果文件不存在,则返回`defaultValue`参数。
335+
- 如果文件存在且提供`defaultValue`参数,则会深度合并对象。
336+
337+
## readJsonFileAsync
338+
339+
readJsonFile的异步版本

docs/guide/string.md

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -499,4 +499,15 @@ test("Matcher",() => {
499499
expect(matcher.test("myapp/src/test/ss.ts")).toBe(false)
500500
expect(matcher.test("myapp/src/test/ss.js")).toBe(true)
501501
})
502-
```
502+
```
503+
504+
505+
## trimChars
506+
507+
去掉字符串前后的指定字符
508+
509+
```typescript
510+
"<[abc123xyz]>".trimChars("abc","<>[]") // == "123xyz"
511+
"'abc123xyz'".trimChars("xyz") // == "abc123"
512+
```
513+

src/fs/copyFiles.ts

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,15 @@ export interface CopyFilesOptions {
4141
error? : (error:Error,{source,target}:{source: string, target: string})=>void | typeof ABORT // 复制出错的回调
4242
templateOptions?: Record<string, any> | ((file: string) => Record<string, any> | Promise<Record<string, any>>);
4343
}
44-
45-
export async function copyFiles( pattern: string, targetDir: string, options?: CopyFilesOptions) {
44+
/**
45+
* 拷贝满足条件的文件到目标文件夹
46+
*
47+
* @param pattern
48+
* @param targetDir
49+
* @param options
50+
* @returns 返回实际拷贝的文件列表
51+
*/
52+
export async function copyFiles( pattern: string, targetDir: string, options?: CopyFilesOptions):Promise<string[]> {
4653

4754
const opts = assignObject({
4855
ignore : [],
@@ -62,8 +69,10 @@ export async function copyFiles( pattern: string, targetDir: string, options?: C
6269
if (opts.clean) {
6370
try{await cleanDir(targetDir)}catch{}
6471
}
72+
73+
const copyedFiles:string[] = []
6574

66-
return new Promise<void>((resolve, reject) => {
75+
return new Promise<string[]>((resolve, reject) => {
6776
glob(pattern, {
6877
ignore,
6978
cwd:srcDir,
@@ -92,6 +101,7 @@ export async function copyFiles( pattern: string, targetDir: string, options?: C
92101
}
93102
try {
94103
await copyFile(fromFile, toFile, opts);
104+
copyedFiles.push(toFile)
95105
if (typeof options?.after == "function") {
96106
if(options.after(fileInfo)===ABORT){
97107
break
@@ -105,7 +115,7 @@ export async function copyFiles( pattern: string, targetDir: string, options?: C
105115
}
106116
}
107117
}
108-
resolve();
118+
resolve(copyedFiles);
109119
}).catch(reject);
110120
});
111121
}

src/fs/fileIsExists.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,17 @@ export function fileIsExists(filename:string):boolean{
1010
}catch{
1111
return false
1212
}
13+
}
14+
15+
/**
16+
* 异步检查文件是否存在
17+
* @param filename
18+
*/
19+
export async function fileIsExistsAsync(filename: string): Promise<boolean> {
20+
try {
21+
await fs.promises.stat(filename);
22+
return true;
23+
} catch {
24+
return false;
25+
}
1326
}

src/fs/index.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,6 @@ export * from "./getExistedDir"
66
export * from "./fileIsExists"
77
export * from "./copyFiles"
88
export * from "./copyDirs"
9-
export * from "./copyFile"
9+
export * from "./copyFile"
10+
export * from "./writeJsonFile"
11+
export * from "./readJsonFile"

src/fs/readJsonFile.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
2+
import fs from 'node:fs'
3+
import { deepMerge } from '../object/deepMerge';
4+
import { promises as fsPromises } from 'node:fs';
5+
6+
export function readJsonFile(jsonfile: string,defaultValue?:Record<string,any>) {
7+
let json = {}
8+
if(fs.existsSync(jsonfile)){
9+
json = JSON.parse(fs.readFileSync(jsonfile,{encoding:'utf-8'}).toString())
10+
}
11+
if(defaultValue){
12+
json = deepMerge({},defaultValue,json)
13+
}
14+
return json
15+
}
16+
17+
export async function readJsonFileAsync(jsonfile: string, defaultValue?: Record<string, any>) {
18+
let json = {};
19+
if (await fsPromises.access(jsonfile).then(() => true).catch(() => false)) {
20+
json = JSON.parse((await fsPromises.readFile(jsonfile, { encoding: 'utf-8' })).toString());
21+
}
22+
if (defaultValue) {
23+
json = deepMerge({}, defaultValue, json);
24+
}
25+
return json;
26+
}

src/fs/writeJsonFile.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
2+
import fs from 'node:fs';
3+
import { deepMerge } from '../object/deepMerge';
4+
import { promises as fsPromises } from 'node:fs';
5+
6+
export function writeJsonFile(jsonfile: string, data:Record<string,any>) {
7+
let json = {}
8+
if(fs.existsSync(jsonfile)){
9+
json = JSON.parse(fs.readFileSync(jsonfile,{encoding:'utf-8'}).toString())
10+
}
11+
json = deepMerge(json,data)
12+
fs.writeFileSync(jsonfile,JSON.stringify(json,null,4))
13+
return json
14+
15+
}
16+
17+
export async function writeJsonFileAsync(jsonfile: string, data: Record<string, any>) {
18+
let json = {};
19+
if (await fsPromises.stat(jsonfile).then(() => true).catch(() => false)) {
20+
const fileContent = await fsPromises.readFile(jsonfile, { encoding: 'utf-8' });
21+
json = JSON.parse(fileContent.toString());
22+
}
23+
json = deepMerge(json, data);
24+
await fsPromises.writeFile(jsonfile, JSON.stringify(json, null, 4));
25+
return json;
26+
}

src/string/trimChars.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
2+
/**
3+
* 移除字符串前后的字符
4+
*
5+
* trimChars(" hello world ") => "hello world"
6+
* trimChars(" \nhello world\n ") => "hello world"
7+
*
8+
* @param {*} str
9+
* @param {*} chars
10+
* @returns
11+
*/
12+
export function trimChars(str:string,chars:string=`"'`){
13+
let start = 0
14+
let end = str.length
15+
const arrChars = chars.split('')
16+
while(start<end && arrChars.includes(str[start])){
17+
start++
18+
}
19+
while(end>start && arrChars.includes(str[end-1])){
20+
end--
21+
}
22+
return str.substring(start,end)
23+
}
24+
25+
String.prototype.trimChars=function(this:string,chars:string){
26+
return trimChars(this,chars)
27+
}
28+
29+
declare global {
30+
interface String {
31+
trimChars(chars: string): string
32+
}
33+
}

0 commit comments

Comments
 (0)