Skip to content

Utils Helper Functions

This file provides a collection of utility functions for path handling, process management, JSON validation, PID file operations, and data formatting in the @sodacore/core library.


Features

  • Path Utilities: Normalize and resolve file paths across platforms.
  • Process Utilities: Manage PID files and retrieve thread file arguments.
  • JSON Utilities: Check if data is valid JSON or serializable.
  • Script Packet Parsing: Parse incoming script packets for command/context extraction.
  • Byte Formatting: Convert byte values to human-readable strings.

Usage

typescript
import {
	normalise,
	resolve,
	getThreadFileFromArgs,
	isJson,
	isConvertable,
	writePid,
	removePid,
	getFilePath,
	parseScriptPacket,
	formatBytes
} from './helper/utils';

const normalized = normalise('C:\\path\\to\\file');
const absolute = resolve('/base/path', '../other/file.js');
const threadFile = getThreadFileFromArgs();
const validJson = isJson('{"foo": "bar"}');
const canConvert = isConvertable({ foo: 'bar' });
await writePid('my-service');
await removePid('my-service');
const filePath = getFilePath('./config.json');
const packet = parseScriptPacket('{"command":"run","context":{}}');
const readable = formatBytes(10240);

API

normalise(path: string): string

Converts a path to a standard format, replacing Windows backslashes with forward slashes.

resolve(base: string, ...paths: string[]): string

Resolves a base path with additional path segments, handling ./ and ../ navigation.

getThreadFileFromArgs(): string

Retrieves the filename passed to worker/thread bootstrap processes via the --file= argument.

isJson(data: string): boolean

Checks if a string is valid JSON.

isConvertable(value: any): boolean

Checks if a value can be serialized to JSON.

writePid(name?: string): Promise<void>

Writes a PID file for the current process. Throws if the file already exists.

removePid(name?: string): Promise<void>

Removes a PID file for the given process name. Throws if the file does not exist.

getFilePath(path: string): string

Returns a file path based on the NODE_ENV environment variable. Uses the current file in development, or resolves the path in production.

parseScriptPacket(data: string): { command: string, context: Record<string, any> } | null

Parses a script packet from a JSON string, extracting the command and context. Returns null if invalid.

formatBytes(bytes: number, decimals = 2, isBinary = false): string

Formats a byte value into a human-readable string (e.g., 10.24 KB). Supports binary (1024) and decimal (1000) units.


Notes

  • PID file operations are currently not in use due to Bun's process handling limitations.
  • These utilities are designed to be used throughout the core library for consistency and reliability.

Released under the Apache-2.0 License.