Skip to content

Instantly share code, notes, and snippets.

@mmyoji
Created September 27, 2021 04:09
Show Gist options
  • Save mmyoji/dedf0efa61bbc42941a313c1c4397b6f to your computer and use it in GitHub Desktop.
Save mmyoji/dedf0efa61bbc42941a313c1c4397b6f to your computer and use it in GitHub Desktop.
[Node.js] TmpFile class
// 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);
// 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