Created
September 27, 2021 04:09
-
-
Save mmyoji/dedf0efa61bbc42941a313c1c4397b6f to your computer and use it in GitHub Desktop.
[Node.js] TmpFile class
This file contains hidden or 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
// src/index.ts | |
async function main() { | |
const tmpFile = new TmpFile(); | |
const data = { name: "foo", age: 30 }; | |
await tmpFile.write("users/1.json", JSON.stringify(data)); | |
console.log(await tmpFile.read("users/1.json")); | |
} | |
main().catch(console.error); |
This file contains hidden or 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
// src/core/tmp-file.ts | |
import { readFile, writeFile, mkdir } from "fs/promises"; | |
import { resolve, dirname } from "path"; | |
// Suppose having `tmp` dir on the project root. | |
export class TmpFile { | |
async read(path: string): Promise<string> { | |
const fpath = this.getFilePath(path); | |
await this.prepare(fpath); | |
const buf = await readFile(fpath); | |
return buf.toString(); | |
} | |
async write(path: string, data: string): Promise<void> { | |
const fpath = this.getFilePath(path); | |
await this.prepare(fpath); | |
await writeFile(fpath, data); | |
} | |
private async prepare(path: string) { | |
const dirPath = dirname(path); | |
console.log(`dirPath=${dirPath}`); | |
await mkdir(dirPath, { recursive: true }); | |
} | |
private getFilePath(path: string) { | |
return this.getRootPath() + "/" + path; | |
} | |
private getRootPath() { | |
return resolve(__dirname, "../../tmp"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment