Skip to content

Introduction

Utility function collection. Provides object deep merge, environment detection, JSON file operations, IP/port utilities, and common helper functions. All sub-module APIs are unified under the ee-core/utils export path.

See also: ps for process state and path utilities | helper (same page)

Import

javascript
// ESM
import { extend, is, strictParse, fnDebounce, getPort, publicIpv4 } from 'ee-core/utils';

// CJS
const { extend, is, strictParse, fnDebounce, getPort, publicIpv4 } = require('ee-core/utils');

All functions from sub-modules (extend, is, json, pargv, wrap, helper, port, ip) and top-level functions (getPackage, getMAC, machineId, etc.) are available via ee-core/utils.


Top-level Functions

getPackage()

Read and parse package.json from the project root directory.

Returns: unknown — Parsed package.json object.

Example:

javascript
const pkg = getPackage();
console.log(pkg.name, pkg.version);

getMAC(iface?)

Get the first valid MAC address. Traverses local network interfaces, skipping zero MAC addresses (virtual interfaces).

Parameters:

ParameterTypeRequiredDescription
ifacestringNoSpecify network interface name; if omitted, all interfaces are traversed

Returns: string — First valid MAC address.

Throws: If specified interface doesn't exist, has no valid MAC, or no valid MAC globally.

isMAC(macAddress)

Check if input is a valid MAC address format (XX:XX:XX:XX:XX:XX or XX-XX-XX-XX-XX-XX).

Parameters:

ParameterTypeRequiredDescription
macAddressstringYesString to check

Returns: boolean

machineIdSync(original?)

Synchronously get machine unique identifier (hash value).

Parameters:

ParameterTypeRequiredDescription
originalbooleanNoReturn original value instead of SHA-256 hash. Default: false

Returns: string — Machine unique identifier.

machineId(original?)

Asynchronously get machine unique identifier (hash value). Suitable for scenarios where blocking the event loop is undesirable.

Parameters:

ParameterTypeRequiredDescription
originalbooleanNoReturn original value instead of SHA-256 hash. Default: false

Returns: Promise<string> — Machine unique identifier.

getPlatform(delimiter?, isDiffArch?)

Get platform identifier string for build artifact naming and platform detection.

Parameters:

ParameterTypeRequiredDescription
delimiterstringNoSeparator. Default: '_'
isDiffArchbooleanNoDistinguish architecture bitness (Windows only). Default: false

Returns: string — Platform identifier (e.g. 'windows_64', 'macos_apple', 'linux').

isFileProtocol(protocol)

Check if protocol is file://.

Parameters:

ParameterTypeRequiredDescription
protocolstringYesProtocol string

Returns: boolean

isWebProtocol(protocol)

Check if protocol is http:// or https://.

Parameters:

ParameterTypeRequiredDescription
protocolstringYesProtocol string

Returns: boolean

isJsProject(baseDir)

Check if the project is a JavaScript project (not TypeScript). Determines by checking if electron/main.js or electron/index.js exists.

Parameters:

ParameterTypeRequiredDescription
baseDirstringYesProject root directory

Returns: boolean


extend

Object deep merge utility. Core implementation for framework configuration layer merging.

extend(deep, target, ...sources)

Merge properties from multiple source objects into the target object.

Parameters:

ParameterTypeRequiredDescription
deepboolean | ExtendOptionsYesWhether to deep merge. true = recursive merge for plain objects
targetTYesTarget object, merge result written here
sourcesArray<Partial<T>>NoSource objects, merged in order

Returns: T — Merged target object.

Merge rules:

  • Shallow merge (deep=false): source properties directly overwrite target
  • Deep merge (deep=true): plain objects are recursively merged, non-plain-objects overwritten
  • Skips __proto__ (prevents prototype pollution)
  • Skips undefined values
  • Detects self-references (prevents infinite recursion)

Example:

javascript
// Shallow merge
extend(false, { a: 1 }, { a: 2, b: 3 }); // { a: 2, b: 3 }

// Deep merge
extend(true, { a: { x: 1 } }, { a: { y: 2 } }); // { a: { x: 1, y: 2 } }

is

Electron runtime environment detection. Exported as a namespace object.

javascript
// ESM
import { is } from 'ee-core/utils';
if (is.all(is.main, is.osx)) { /* main process + macOS */ }

// CJS
const { is } = require('ee-core/utils');

Detection Functions

FunctionReturnsDescription
is.renderer()booleanCurrently in renderer process (process.type === 'renderer')
is.main()booleanCurrently in main process (process.type === 'browser')
is.osx()booleanOperating system is macOS (process.platform === 'darwin')
is.macOS()booleanAlias for osx()
is.windows()booleanOperating system is Windows (process.platform === 'win32')
is.linux()booleanOperating system is Linux
is.openharmony()booleanOperating system is OpenHarmony
is.x86()booleanProcessor is x86 (32-bit, process.arch === 'ia32')
is.x64()booleanProcessor is x64 (64-bit, process.arch === 'x64')
is.sandbox()booleanRunning in macOS sandbox
is.mas()booleanMac App Store build (process.mas === true)
is.windowsStore()booleanWindows Store build (process.windowsStore === true)

Combinators

FunctionSignatureDescription
is.all(...fn)(...() => boolean) => boolean | undefinedAll conditions true
is.none(...fn)(...() => boolean) => boolean | undefinedAll conditions false
is.one(...fn)(...() => boolean) => boolean | undefinedAt least one condition true

Example:

javascript
if (is.all(is.main, is.osx)) {
  // Only runs in main process on macOS
}

if (is.none(is.renderer, is.windows)) {
  // Not renderer process, not Windows
}

json

JSON file read/write utility. Provides synchronous and asynchronous operations.

strictParse(str)

Parse JSON string with validation that result must be an object.

Parameters:

ParameterTypeRequiredDescription
strstringYesJSON string

Returns: unknown — Parsed object.

Throws: If result is not an object type.

readSync(filepath)

Synchronously read and parse a JSON file.

Parameters:

ParameterTypeRequiredDescription
filepathstringYesJSON file path

Returns: unknown — Parsed object.

Throws: If file does not exist.

writeSync(filepath, str, options?)

Synchronously write a JSON file. Auto-creates target directory. Default 2-space indentation.

Parameters:

ParameterTypeRequiredDescription
filepathstringYesTarget file path
strunknownYesContent to write (objects auto-serialized)
optionsJsonWriteOptionsNo{ space?: number, replacer?: Function }

Returns: void

read(filepath)

Asynchronously read and parse a JSON file.

Parameters:

ParameterTypeRequiredDescription
filepathstringYesJSON file path

Returns: Promise<unknown> — Parsed object.

write(filepath, str, options?)

Asynchronously write a JSON file. Auto-creates target directory.

Parameters:

ParameterTypeRequiredDescription
filepathstringYesTarget file path
strunknownYesContent to write
optionsJsonWriteOptionsNo{ space?: number, replacer?: Function }

Returns: Promise<void>


helper

Common utility function collection.

fnDebounce()

Create debounce wrapper factory. Returns a function that applies debounce control to any passed function.

Returns: Debounce wrapper function with signature (fn, delayTime?, isImedite?, args?) => void

Example:

javascript
const debounce = fnDebounce();
debounce(myFunction, 300, false, data);  // Debounced
debounce(myFunction, 0, true, data);     // Immediate (no debounce)

getRandomString()

Generate an approximately 10-character random alphanumeric string. Not for security scenarios.

Returns: string (e.g. 'x3k9m2a1b5')

mkdir(filepath, opt?)

Recursively create directory. No error if already exists (mkdir -p equivalent).

Parameters:

ParameterTypeRequiredDescription
filepathstringYesDirectory path
opt{ mode?: number }NoDirectory permissions

Returns: void

chmodPath(filepath, mode)

Recursively modify file and directory permissions.

Parameters:

ParameterTypeRequiredDescription
filepathstringYesTarget directory path
modenumberYesPermission value (e.g. 0o755)

Returns: void

compareVersion(v1, v2)

Compare two semantic version numbers.

Parameters:

ParameterTypeRequiredDescription
v1stringYesFirst version (e.g. '1.2.3')
v2stringYesSecond version (e.g. '1.3.0')

Returns: number1 if v1 > v2, -1 if v1 < v2, 0 if equal.

stringify(obj, ignore?)

Serialize object to JSON string, excluding specified fields.

Parameters:

ParameterTypeRequiredDescription
objRecord<string, unknown>YesObject to serialize
ignorestring[]NoProperty names to exclude

Returns: string — Filtered JSON string.

validValue(value)

Check if value is non-null, non-undefined, and non-empty string.

Parameters:

ParameterTypeRequiredDescription
valueunknownYesValue to check

Returns: boolean

checkConfig(prop)

Check if a configuration file exists under the project root.

Parameters:

ParameterTypeRequiredDescription
propstringYesFile path relative to project root

Returns: boolean

sleep(ms)

Async sleep. Returns a Promise that resolves after the specified milliseconds.

Parameters:

ParameterTypeRequiredDescription
msnumberYesSleep time (ms)

Returns: Promise<void>

systemSleep(ms)

Synchronous blocking sleep. Blocks the current thread. Not suitable for renderer process (will freeze UI).

Parameters:

ParameterTypeRequiredDescription
msnumberYesSleep time (ms), must be >= 0

Returns: void

Implementation: Prefer Atomics.wait (zero CPU), fallback to busy-wait loop.

replaceArgsValue(argv, key, value)

Replace a key=value parameter in command line argument array.

Parameters:

ParameterTypeRequiredDescription
argvstring[]YesArgument array
keystringYesParameter key name
valuestringYesNew value

Returns: string[] — Modified argv array.

Example:

javascript
replaceArgsValue(['--port=8080', '--env=dev'], 'port', '9090')
// => ['--port=9090', '--env=dev']

getValueFromArgv(argv, key)

Get the value of a specified key from command line arguments.

Parameters:

ParameterTypeRequiredDescription
argvstring[]YesArgument array
keystringYesKey name

Returns: unknown — Value or undefined if not found.

fileIsExist(filepath)

Check if a file exists (stat-based).

Parameters:

ParameterTypeRequiredDescription
filepathstringYesFile path

Returns: boolean


port

TCP port allocation utility with locking mechanism.

getPort(options?)

Find an available TCP port.

Parameters:

ParameterTypeRequiredDescription
optionsGetPortOptionsNoPort search options

GetPortOptions:

FieldTypeDescription
portnumber | number[]Preferred port or range. 0 = OS auto-assign
hoststringBound host. Unspecified = check all interfaces

Returns: Promise<number> — Available port number.

Example:

javascript
const port = await getPort();                    // OS auto-assign
const port = await getPort({ port: 3000 });      // Try 3000, auto-find if occupied
const port = await getPort({ port: [3000, 3001] }); // Try list

releasePortLocks()

Clean up port lock resources (rotation timer + locked port sets). Call during app shutdown.

Returns: void


ip

Public IP address query utility. Supports DNS, HTTPS, and combined query methods.

publicIpv4(options?)

Query public IPv4 address.

Parameters:

ParameterTypeRequiredDescription
optionsIpOptionsNo`{ type?: 'http'

Returns: Promise<string> & { cancel?: () => void } — IPv4 address with cancel method.

Example:

javascript
const p = publicIpv4({ type: 'http', timeout: 5000 });
const ip = await p;
// Or cancel: p.cancel();

publicIpv6(options?)

Query public IPv6 address. Same options and return type as publicIpv4.

Returns: Promise<string> & { cancel?: () => void } — IPv6 address with cancel method.