-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Co-authored-by: Mohammad Honarvar <[email protected]>
- Loading branch information
1 parent
73bb495
commit 659b2ea
Showing
3 changed files
with
45 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
import {createLogger} from '@alwatr/logger'; | ||
export const logger = createLogger('alwatr/util'); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
import {existsSync, readFileSync, writeFileSync, renameSync, mkdirSync} from 'node:fs'; | ||
import {rename, mkdir, writeFile, readFile} from 'node:fs/promises'; | ||
import {dirname} from 'node:path'; | ||
|
||
import {logger} from './_logger.js'; | ||
|
||
/** | ||
* Enhanced read json file. | ||
* @example | ||
* const fileContent = readJsonFileSync('./file.json'); | ||
*/ | ||
export const readJsonFileSync = <T>(path: string): T | null => { | ||
logger.logMethodArgs?.('readJsonFileSync', path); | ||
|
||
if (!existsSync(path)) { | ||
return null; | ||
} | ||
|
||
const timeKey = path.substring(path.lastIndexOf('/') + 1); | ||
logger.time?.(`readJsonFileSync(${timeKey})`); | ||
|
||
let fileContent: string; | ||
try { | ||
fileContent = readFileSync(path, {encoding: 'utf-8', flag: 'r'}); | ||
} | ||
catch (err) { | ||
logger.error('readJsonFileSync', 'read_file_failed', err); | ||
throw new Error('read_file_failed'); | ||
} | ||
|
||
let data; | ||
try { | ||
data = JSON.parse(fileContent) as T; | ||
} | ||
catch (err) { | ||
logger.error('readJsonFileSync', 'invalid_json', err); | ||
throw new Error('invalid_json'); | ||
} | ||
|
||
console.timeEnd(`readJsonFileSync(${timeKey})`); | ||
return data; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export * from './fs.js'; |