kaven-utils
Version:
Utils for Node.js.
101 lines (100 loc) • 2.5 kB
JavaScript
/********************************************************************
* @author: Kaven
* @email: kaven@wuwenkai.com
* @website: http://blog.kaven.xyz
* @file: [Kaven-Utils] /src/KavenUtility.Constant.ts
* @create: 2021-03-19 12:19:28.048
* @modify: 2024-11-01 14:20:10.229
* @version: 5.4.5
* @times: 21
* @lines: 117
* @copyright: Copyright © 2021-2024 Kaven. All Rights Reserved.
* @description: [description]
* @license: [license]
********************************************************************/
import { Strings_false, Strings_true } from "kaven-basic";
import { dirname } from "node:path";
/**
*
* @since 4.0.0
* @version 2024-11-01
* @returns
*/
export function GetEntryFile() {
// If in CommonJS, use require.main.filename (support for both CJS and ESM)
if (typeof require !== "undefined" && require?.main?.filename) {
return require.main.filename;
}
// In ESM, use import.meta.url and compare with process.argv[1]
if (import.meta && import.meta.url) {
const currentFile = new URL(import.meta.url).pathname;
const entryFile = process.argv[1];
// Convert entryFile to the same format as currentFile for comparison
if (currentFile === new URL(`file://${entryFile}`).pathname) {
return entryFile;
}
}
// Default return (fallback to process.argv[1] if no main filename found)
return process.argv[1];
}
/**
*
* @since 4.0.0
* @version 2023-11-19
* @returns
*/
export function GetEntryDirectory() {
const file = GetEntryFile() ?? process.cwd();
return dirname(file);
}
/**
* `process.env`
* @param name
* @returns
* @since 2.0.14
* @version 2021-03-19
*/
export function GetEnv(name) {
return process.env[name];
}
/**
*
* @param name
* @returns
* @since 4.3.5
* @version 2022-09-15
*/
export function GetEnvBoolean(name) {
const s = GetEnv(name);
if (s === Strings_true) {
return true;
}
if (s === Strings_false) {
return false;
}
return undefined;
}
/**
*
* @param name
* @returns
* @since 4.1.0
* @version 2024-11-01
*/
export function GetEnvJson(name) {
const str = GetEnv(name);
if (!str) {
return undefined;
}
return JSON.parse(str);
}
/**
* @since 1.1.21
* @version 2018-11-05
*/
export const Platform = process.platform;
/**
* @since 1.1.21
* @version 2018-11-05
*/
export const IsWin32 = Platform === "win32";