@guanghechen/resource
v2.0.1
Published
<header> <h1 align="center"> <a href="https://github.com/guanghechen/sora/tree/@guanghechen/[email protected]/packages/resource#readme">@guanghechen/resource</a> </h1> <div align="center"> <a href="https://www.npmjs.com/package/@guanghechen/res
Readme
Text resource abstraction with file-based and memory-based implementations. Implements the
ITextResource interface for unified resource management with load, save, and destroy operations.
Install
npm
npm install --save @guanghechen/resourceyarn
yarn add @guanghechen/resource
Usage
FileTextResource
File-based text resource:
import { FileTextResource } from '@guanghechen/resource'
const resource = new FileTextResource({
filepath: '/path/to/config.json',
encoding: 'utf8',
strict: false, // If true, throws when file doesn't exist on load
})
// Check existence
const exists = await resource.exists() // true/false
// Load content
const content = await resource.load()
if (content) {
console.log('Loaded:', content)
}
// Save content (creates parent directories if needed)
await resource.save('{"key": "value"}')
// Delete file
await resource.destroy()MemoTextResource
In-memory text resource (useful for testing):
import { MemoTextResource } from '@guanghechen/resource'
const resource = new MemoTextResource({
content: 'initial content',
encoding: 'utf8',
strict: false, // If true, throws on load/save after destroy
})
// Load content
const content = await resource.load() // 'initial content'
// Save new content
await resource.save('updated content')
// Check if resource is alive
const exists = await resource.exists() // true
// Destroy (marks as not alive)
await resource.destroy()
await resource.exists() // falseStrict Mode
Both resources support strict mode for error handling:
import { FileTextResource, MemoTextResource } from '@guanghechen/resource'
// Strict file resource - throws if file doesn't exist
const strictFile = new FileTextResource({
filepath: '/nonexistent/file.txt',
encoding: 'utf8',
strict: true,
})
await strictFile.load() // throws Error
// Strict memo resource - throws after destroy
const strictMemo = new MemoTextResource({
content: 'data',
encoding: 'utf8',
strict: true,
})
await strictMemo.destroy()
await strictMemo.load() // throws Error