utils/src/utils.ts

68 lines
1.8 KiB
TypeScript

import chalk from "chalk";
import fs from "fs";
import json5 from "json5";
export interface ErrorWithCode {
code: string;
}
export const convertCamelToUpperSnakeCase = (str: string) =>
str.replace(/[A-Z]/g, (letter) => `_${letter}`).toUpperCase();
/**
* From: https://www.webmanajemen.com/2022/05/use-import-meta-cjs.html
*/
export const getDirname = () => {
// get the stack
const { stack } = new Error();
// get the third line (the original invoker)
const invokeFileLine = (stack || "").split(`\n`)[2];
// match the file url from file://(.+.(ts|js)) and get the first capturing group
const __filename = (invokeFileLine.match(/file:\/\/(.+.(ts|js))/) ||
[])[1].slice(1);
// match the file URL from file://(.+)/ and get the first capturing group
// the (.+) is a greedy quantifier and will make the RegExp expand to the largest match
const __dirname = (invokeFileLine.match(/file:\/\/(.+)\//) || [])[1].slice(1);
return { __dirname, __filename };
};
export const getTime = () => {
const now = new Date(),
tzo = -now.getTimezoneOffset(),
dif = tzo >= 0 ? "+" : "-",
pad = (num: number) => {
const norm = Math.floor(Math.abs(num));
return `${norm < 10 ? "0" : ""}${norm}`;
};
return [
now.getFullYear(),
"-",
pad(now.getMonth() + 1),
"-",
pad(now.getDate()),
"T",
pad(now.getHours()),
":",
pad(now.getMinutes()),
":",
pad(now.getSeconds()),
dif,
pad(tzo / 60),
":",
pad(tzo % 60),
].join("");
};
export const log = (...msg: unknown[]) =>
console.log(`${chalk.grey(`${getTime()}:`)} ${msg}`);
export const readJsonIfExists = (filePath: string | URL) => {
try {
return json5.parse(fs.readFileSync(filePath, { encoding: "utf8" }));
} catch (err) {
// if no file, return empty object
if ((err as ErrorWithCode)?.code === "ENOENT") return {};
throw err;
}
};