Skip to content

Commit

Permalink
add readJson
Browse files Browse the repository at this point in the history
  • Loading branch information
gutenye committed Nov 9, 2024
1 parent b3afa95 commit 047f765
Show file tree
Hide file tree
Showing 4 changed files with 126 additions and 16 deletions.
File renamed without changes.
91 changes: 76 additions & 15 deletions packages/fs/__tests__/fsUtils.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { afterEach, beforeEach, expect, it, mock } from 'bun:test'
import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test'
import nodeFs from 'node:fs/promises'
import Memfs, { vol } from 'memfs'
import fsUtils from '../fsUtils'
Expand All @@ -12,35 +12,96 @@ mock.module('node:fs/promises', () => ({ default: menfs }))
beforeEach(() => {
vol.fromJSON({
'/a.txt': 'a.txt',
'/a.json': '{"a":1}',
})
})

afterEach(() => {
vol.reset()
})

it('pathExists: none-exist', async () => {
expect(await fsUtils.pathExists('/none-exist/a.txt')).toBeFalsy()
describe('pathExists', () => {
it('pathExists: none-exist', async () => {
expect(await fsUtils.pathExists('/none-exist/a.txt')).toBeFalsy()
})

it('pathExists: exist', async () => {
expect(await fsUtils.pathExists('/a.txt')).toBeTruthy()
})
})

it('pathExists: exist', async () => {
expect(await fsUtils.pathExists('/a.txt')).toBeTruthy()
describe('inputFile', () => {
it('inputFile: none-exist', async () => {
expect(await fsUtils.inputFile('/none-exist/a.txt', 'utf8')).toBeUndefined()
})

it('inputFile: exist', async () => {
expect(await fsUtils.inputFile('/a.txt', 'utf8')).toEqual('a.txt')
})
})

it('inputFile: none-exist', async () => {
expect(await fsUtils.inputFile('/none-exist/a.txt', 'utf8')).toBeUndefined()
describe('outputFile', () => {
it('outputFile: none-exist', async () => {
await fsUtils.outputFile('/none-exist/a.txt', 'new')
expect(await nodeFs.readFile('/none-exist/a.txt', 'utf8')).toEqual('new')
})

it('outputFile: exist', async () => {
await fsUtils.outputFile('/a.txt', 'new')
expect(await nodeFs.readFile('/a.txt', 'utf8')).toEqual('new')
})
})

it('inputFile: exist', async () => {
expect(await fsUtils.inputFile('/a.txt', 'utf8')).toEqual('a.txt')
describe('inputJson', () => {
it('file not exist', async () => {
expect(await fsUtils.inputJson('/none-exist/a.json')).toBeUndefined()
})
it('file exist', async () => {
expect(await fsUtils.inputJson('/a.json')).toEqual({ a: 1 })
})
it('invalid json', async () => {
await expect(() => fsUtils.inputJson('/a.txt')).toThrow(
`[inputJson] JSON Parse error: Unexpected identifier "a" from '/a.txt'`,
)
})
})

it('outputFile: none-exist', async () => {
await fsUtils.outputFile('/none-exist/a.txt', 'new')
expect(await nodeFs.readFile('/none-exist/a.txt', 'utf8')).toEqual('new')
describe('readJson', () => {
it('file not exist', async () => {
await expect(() => fsUtils.readJson('/none-exist/a.json')).toThrow(
`ENOENT: no such file or directory, open '/none-exist/a.json'`,
)
})
it('file exist', async () => {
expect(await fsUtils.readJson('/a.json')).toEqual({ a: 1 })
})
it('invalid json', async () => {
await expect(() => fsUtils.readJson('/a.txt')).toThrow(
`[readJson] JSON Parse error: Unexpected identifier "a" from '/a.txt'`,
)
})
})

it('outputFile: exist', async () => {
await fsUtils.outputFile('/a.txt', 'new')
expect(await nodeFs.readFile('/a.txt', 'utf8')).toEqual('new')
/*
describe('walk', async () => {
vol.fromJSON({
'/dir/a.txt': '',
'/dir/sub/b.txt': '',
})
const entries = []
for await (const entry of fsUtils.walk('/dir')) {
entries.push(entry)
}
expect(entries).toEqual([
{
path: '/dir/sub/b.txt',
relativePath: 'sub/b.txt',
dir: '/dir/sub',
base: 'b.txt',
name: 'b',
ext: '.txt',
},
])
})
*/
49 changes: 49 additions & 0 deletions packages/fs/fsUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,52 @@ async function outputFile(
// TODO
// emptyDir: readdirSync(dir).forEach(v => fs.rmSync(`${dir}/${v}`, { recursive: true })

/**
* Walk dir
*/

async function* walk(dir: string): AsyncGenerator<string> {
for await (const d of await fs.opendir(dir)) {
console.log({ dir, d })
const entry = nodePath.join(dir, d.name)
if (d.isDirectory()) yield* walk(entry)
else if (d.isFile()) yield entry
}
}

/**
* - uses inputFile
*/
async function inputJson(input: ReadFileArgs[0], options?: ReadFileArgs[1]) {
const text = await inputFile(input, options)
if (!text) {
return
}
try {
return JSON.parse(text)
} catch (error) {
if (error instanceof Error) {
throw new Error(`[inputJson] ${error.message} from '${input}'`)
}
throw error
}
}

/*
* - uses readFile
*/
async function readJson(input: ReadFileArgs[0], options?: ReadFileArgs[1]) {
const text = await fs.readFile(input, options)
try {
return JSON.parse(text)
} catch (error) {
if (error instanceof Error) {
throw new Error(`[readJson] ${error.message} from '${input}'`)
}
throw error
}
}

/**
* TS check if error is a Node Error
*/
Expand All @@ -66,4 +112,7 @@ export default {
inputFile,
outputFile,
isNodeError,
readJson,
inputJson,
walk,
}
2 changes: 1 addition & 1 deletion packages/js/jsUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Features
- compatible with lodash
*/

/* new methods */
/* New methods */

export async function findAsync<T>(
items: T[],
Expand Down

0 comments on commit 047f765

Please sign in to comment.