@hyperfrontend/project-scope/core/fs

fs

Safe, typed wrappers around Node.js synchronous filesystem APIs with structured error handling.

Covers four areas: reading (readFileContent, readFileBuffer, readJsonFile, plus *IfExists variants), writing (writeFileContent, writeJsonFile, ensureDir, automatically creates parent directories), directory operations (readDirectory, readDirectoryRecursive, createDirectory, removeDirectory), and stat/traversal helpers (exists, isFile, isDirectory, isSymlink, findUpwardWhere, locateByMarkers, traverseUpward).

All operations surface failures via createFileSystemError with codes (FS_NOT_FOUND, FS_READ_ERROR, FS_WRITE_ERROR, FS_PARSE_ERROR) carrying contextual paths.

API Reference§

ƒ Functions

§function

createDirectory(dirPath: string, options?: CreateDirectoryOptions): void

Create a directory, optionally creating parent directories.
Parameters
NameTypeDescription
§dirPath
stringPath where the directory should be created
§options?
CreateDirectoryOptionsCreation options
Example

Creating directories

// Create nested directories
createDirectory('./output/reports/2024')

// Create single directory without parents
createDirectory('./logs', { recursive: false })
§function

createFileSystemError(message: string, code: FileSystemErrorCode, context: FileSystemErrorContext): Error

Create a file system error with code and context.
Parameters
NameTypeDescription
§message
stringThe error message describing what went wrong
§code
FileSystemErrorCodeThe category code for this type of filesystem failure
§context
FileSystemErrorContextAdditional context including path, operation, and cause
Returns
Error
A configured Error object with code and context properties
Example

Creating a file system error

throw createFileSystemError(
  'Cannot read file',
  'FS_READ_ERROR',
  { path: './missing.txt', operation: 'read' }
)
§function

ensureDir(dirPath: string): void

Ensure directory exists, create recursively if not.
Parameters
NameTypeDescription
§dirPath
stringDirectory path to ensure exists
Example

Ensuring directory exists

ensureDir('./output/reports')
// Directory now exists (created if missing)
§function

exists(filePath: string): boolean

Check if path exists.
Parameters
NameTypeDescription
§filePath
stringPath to check
Returns
boolean
True if path exists
Example

Checking if path exists

if (exists('./config.json')) {
  const config = readJsonFile('./config.json')
}
§function

findUpwardWhere(startPath: string, test: (dirPath: string) => boolean): string

Find directory where predicate returns true, starting from given path.
Parameters
NameTypeDescription
§startPath
stringStarting directory
§test
(dirPath: string) => booleanFunction to test if directory matches criteria
Returns
string
Matching directory path or null
Example

Finding directory with specific config

// Find directory with a specific config
const configDir = findUpwardWhere('./deep/nested/path', (dir) =>
  existsSync(join(dir, '.eslintrc.js'))
)
§function

getFileStat(filePath: string, followSymlinks: boolean): FileStats

Get file stats with error handling.
Parameters
NameTypeDescription
§filePath
stringPath to file
Returns
FileStats
File stats or null if path doesn't exist
Example

Getting file statistics

const stats = getFileStat('./package.json')
if (stats) {
  console.log(`Size: ${stats.size} bytes`)
  console.log(`Modified: ${stats.modified}`)
}
§function

isDirectory(dirPath: string): boolean

Check if path is a directory.
Parameters
NameTypeDescription
§dirPath
stringPath to check
Returns
boolean
True if path is a directory
Example

Checking if path is a directory

if (isDirectory('./src')) {
  // Path exists and is a directory
}
§function

isFile(filePath: string): boolean

Check if path is a file.
Parameters
NameTypeDescription
§filePath
stringPath to check
Returns
boolean
True if path is a file
Example

Checking if path is a file

if (isFile('./package.json')) {
  // Path exists and is a regular file
}
§function

locateByMarkers(startPath: string, markers: unknown): string

Find directory containing any of the specified marker files.
Parameters
NameTypeDescription
§startPath
stringStarting directory
§markers
unknownArray of marker file names to search for
Returns
string
First directory containing any marker, or null
Example

Finding project root by marker files

// Find project root by looking for common marker files
const projectRoot = locateByMarkers('./src/components', [
  'package.json',
  'nx.json',
  'tsconfig.base.json'
])
// => '/workspace/my-project'
§function

readDirectory(dirPath: string): DirectoryEntry[]

List immediate contents of a directory.
Parameters
NameTypeDescription
§dirPath
stringAbsolute or relative path to the directory
Returns
DirectoryEntry[]
Array of entries with metadata for each file/directory
Example

Listing directory contents

import { readDirectory } from '@hyperfrontend/project-scope'

const entries = readDirectory('./src')
for (const entry of entries) {
  console.log(entry.name, entry.isFile ? 'file' : 'directory')
}
§function

readDirectoryRecursive(dirPath: string, options?: RecursiveOptions): DirectoryEntry[]

List directory contents recursively with depth tracking.
Parameters
NameTypeDescription
§dirPath
stringRoot directory path to start traversal
§options?
RecursiveOptionsConfiguration for depth limit, hidden files, and symlinks
Returns
DirectoryEntry[]
Flat array of all entries found during traversal
Example

Recursive directory listing with options

import { readDirectoryRecursive } from '@hyperfrontend/project-scope'

// List all files up to 3 levels deep
const entries = readDirectoryRecursive('./src', { maxDepth: 3 })

// Include hidden files
const allEntries = readDirectoryRecursive('./project', { includeHidden: true })
§function

readFileBuffer(filePath: string): Buffer

Read file contents as Buffer.
Parameters
NameTypeDescription
§filePath
stringPath to file
Returns
Buffer
File contents as Buffer
Example

Reading file as buffer

const buffer = readFileBuffer('./image.png')
console.log(buffer.length) // File size in bytes
§function

readFileContent(filePath: string, encoding: BufferEncoding): string

Read file contents as string.
Parameters
NameTypeDescription
§filePath
stringPath to file
§encoding
BufferEncodingFile encoding (default: utf-8)(default: 'utf-8')
Returns
string
File contents as string
Example

Reading file contents

import { readFileContent } from '@hyperfrontend/project-scope'

const content = readFileContent('./package.json')
console.log(content) // JSON string
§function

readFileIfExists(filePath: string, encoding: BufferEncoding): string

Read file if exists, return null otherwise.
Parameters
NameTypeDescription
§filePath
stringPath to file
§encoding
BufferEncodingFile encoding (default: utf-8)(default: 'utf-8')
Returns
string
File contents or null if file doesn't exist
Example

Reading file if it exists

const content = readFileIfExists('./optional-config.json')
if (content) {
  // File existed, use content
}
§function

readJsonFile<T>(filePath: string, options?: ReadJsonFileOptions<T>): T

Read and parse JSON file.
Parameters
NameTypeDescription
§filePath
stringPath to JSON file
§options?
ReadJsonFileOptions<T>Parse options
Returns
T
Parsed JSON object
Example

Reading JSON file

import { readJsonFile } from '@hyperfrontend/project-scope'

// Read with type inference
interface Config { port: number }
const config = readJsonFile<Config>('./config.json')

// Read with default fallback
const settings = readJsonFile('./settings.json', { default: {} })
§function

readJsonFileIfExists<T>(filePath: string): T

Read and parse JSON file if exists, return null otherwise.
Parameters
NameTypeDescription
§filePath
stringPath to JSON file
Returns
T
Parsed JSON object or null if file doesn't exist or is invalid
Example

Reading JSON file if it exists

interface UserSettings { theme: string }
const settings = readJsonFileIfExists<UserSettings>('./user-settings.json')
const theme = settings?.theme ?? 'default'
§function

removeDirectory(dirPath: string, options?: RemoveDirectoryOptions): void

Delete a directory from the filesystem.
Parameters
NameTypeDescription
§dirPath
stringPath to the directory to remove
§options?
RemoveDirectoryOptionsRemoval configuration
Example

Removing directories

// Remove directory and all contents
removeDirectory('./temp', { recursive: true })

// Safe removal (no error if missing)
removeDirectory('./cache', { recursive: true, force: true })
§function

traverseUpward(startPath: string, predicate: (dirPath: string) => boolean): string

Generic upward directory traversal. Name avoids similarity to fs.readdir/fs.readdirSync.
Parameters
NameTypeDescription
§startPath
stringStarting directory
§predicate
(dirPath: string) => booleanFunction to test each directory
Returns
string
First matching directory or null
Example

Finding directory containing README

// Find first directory containing a README
const readmeDir = traverseUpward('./src/utils', (dir) =>
  existsSync(join(dir, 'README.md'))
)
// => '/project' or null
§function

writeFileBuffer(filePath: string, content: Buffer, options?: WriteFileOptions): void

Write Buffer to file. Creates parent directories if needed.
Parameters
NameTypeDescription
§filePath
stringAbsolute or relative path to the target file
§content
BufferBuffer containing binary data to write
§options?
WriteFileOptionsOptional write configuration (mode)
Example

Writing binary buffer to file

const imageBuffer = Buffer.from([0x89, 0x50, 0x4e, 0x47])
writeFileBuffer('./output/image.png', imageBuffer)
§function

writeFileContent(filePath: string, content: string, options?: WriteFileOptions): void

Write string content to file. Creates parent directories if needed.
Parameters
NameTypeDescription
§filePath
stringAbsolute or relative path to the target file
§content
stringString content to write to the file
§options?
WriteFileOptionsOptional write configuration (encoding, mode)
Example

Writing text content to file

import { writeFileContent } from '@hyperfrontend/project-scope'

// Write a simple text file
writeFileContent('./output/data.txt', 'Hello, World!')

// Write with custom encoding
writeFileContent('./output/data.txt', 'Content', { encoding: 'utf-8' })
§function

writeJsonFile<T>(filePath: string, data: T, options?: WriteJsonOptions): void

Write JSON data to file with formatting. Creates parent directories if needed.
Parameters
NameTypeDescription
§filePath
stringAbsolute or relative path to the target JSON file
§data
TObject or value to serialize as JSON
§options?
WriteJsonOptionsOptional write configuration (indent, encoding, mode)
Example

Writing JSON data to file

import { writeJsonFile } from '@hyperfrontend/project-scope'

// Write object to JSON file
writeJsonFile('./config.json', { port: 3000, debug: true })

// Write with custom indentation
writeJsonFile('./config.json', data, { indent: 4 })

◈ Interfaces

§interface

DirectoryEntry

Entry metadata for a directory listing.
Properties
§depth?:numberDirectory depth (for recursive listings)
§isDirectory:booleanIs a directory
§isFile:booleanIs a file
§name:stringEntry basename
§path:stringFull path
§interface

FileStats

File statistics.
Properties
§accessed:DateLast access time
§created:DateCreation time
§isDirectory:booleanIs a directory
§isFile:booleanIs a file
§mode:numberFile mode/permissions
§modified:DateModification time
§size:numberFile size in bytes
§interface

FileSystemErrorContext

File system error with code and context.
Properties
§cause?:unknownOriginal error that caused the failure
§operation:"read" | "write" | "stat" | "readdir"The filesystem operation that failed
§path:stringAbsolute or relative path where the error occurred
§interface

ReadJsonFileOptions

Options for reading a JSON file.
Properties
§default?:TDefault value to return if the file is not found
§interface

RecursiveOptions

Options for recursive directory listing.
Properties
§includeHidden?:booleanInclude hidden files (dotfiles)
§maxDepth?:numberMaximum depth (-1 or Infinity for unlimited)
§interface

WriteFileOptions

Options for write operations.
Properties
§encoding?:BufferEncodingFile encoding
§mode?:numberFile mode/permissions
§interface

WriteJsonOptions

Options for JSON write operations.
Properties
§encoding?:BufferEncodingFile encoding
§indent?:numberIndentation spaces (default: 2)
§mode?:numberFile mode/permissions

◆ Types

§type

FileSystemErrorCode

Error codes for file system operations.
type FileSystemErrorCode = "FS_NOT_FOUND" | "FS_READ_ERROR" | "FS_WRITE_ERROR" | "FS_PARSE_ERROR" | "FS_NOT_A_DIRECTORY"