Task: Add write file from string and tests

This commit is contained in:
Sambo Chea 2022-02-15 11:57:23 +07:00
parent 27f9320bda
commit 8453af2efa
Signed by: sombochea
GPG Key ID: 3C7CF22A05D95490
3 changed files with 27 additions and 0 deletions

2
.gitignore vendored
View File

@ -118,3 +118,5 @@ out
.yarn/install-state.gz
.pnp.*
# package-lock.json
ignore/

View File

@ -12,3 +12,17 @@ export const readFileToStringDefaultEncoding = (
export const readFileToJson = (relativeFilePath: string): any => {
return JSON.parse(readFileToStringDefaultEncoding(relativeFilePath))
}
export const writeFileFromString = (
relativeFilePath: string,
content: string
): void => {
const baseDir = path.dirname(relativeFilePath)
const absolutePath = path.resolve(relativeFilePath)
if (!fs.existsSync(baseDir)) {
fs.mkdirSync(baseDir, { recursive: true })
}
fs.writeFileSync(absolutePath, content)
}

11
test/file.test.ts Normal file
View File

@ -0,0 +1,11 @@
import { randomUUID } from "crypto"
import { writeFileFromString } from "../src/util/file.util"
test("Write File from String", () => {
const filePath = "./ignore/test.json"
const fileContent = {
key: randomUUID(),
iv: randomUUID(),
}
writeFileFromString(filePath, JSON.stringify(fileContent))
})