@mrskyenet/read_files
v2.1.1
Published
Helpers for loading small configuration files. The library understands `JSON`, `YAML`/`YML`, `CSV`, `.txt`, shell-style `.env`, plus key formats (`.pem`, `.gpg`, `ssh_authorized_keys`). It always returns a consistent object with the raw text, parsed data,
Readme
@mrskyenet/read_files
Helpers for loading small configuration files. The library understands JSON, YAML/YML, CSV, .txt, shell-style .env, plus key formats (.pem, .gpg, ssh_authorized_keys). It always returns a consistent object with the raw text, parsed data, and a Buffer copy.
Installation
npm install @mrskyenet/read_filesCompatibility
- Runtime: native ES modules only (
"type": "module"). - TypeScript: set
"module": "esnext"(or"nodenext") so imports resolve with.mjsextensions. - CommonJS: not officially supported; use a dynamic import if needed (
const { readFileResource } = await import('@mrskyenet/read_files');).
Usage
Import the helpers you need and feed them file paths or strings you already have in memory:
import { readFileResource, read_json, read_env } from '@mrskyenet/read_files';
const { type, data } = await readFileResource('./config/settings.yml');
console.log(type); // "yml"
console.log(data.service);
const envText = await fs.promises.readFile('.env', 'utf8');
const envConfig = read_env(envText);
const jsonConfig = read_json('{"name":"alice"}');API
All named exports are re-exported from @mrskyenet/read_files/functions/index.mjs for direct access when needed. Helpers include read_json, read_yml, read_csv, read_txt, read_env, read_pem, read_gpg, read_ssh_authorized_keys, and read_authorized_keys for pre-loaded strings, plus readFileResource for reading from disk.
async readFileResource(targetPath: string, options?: { encoding?: string })
Reads the file at targetPath, validates the extension, and returns:
path– absolute path of the file.type– normalized identifier (json,yml,csv,txt,env,pem,gpg,ssh_authorized_keys).raw– raw string contents.data– parsed payload (objectfor JSON/YML/CSV/ENV,stringfor.txtand key-only formats such as PEM/GPG/ssh_authorized_keys).buffer–Buffer.from(raw, encoding)for convenient binary handling.
Files named ssh_authorized_keys (or authorized_keys) are accepted even without a file extension and are returned as raw strings.
Throws
Files containing invisible or control characters (e.g. zero-width spaces, BOM) are rejected to prevent hidden configuration tampering.
TypeErrorwhentargetPathis missing/falsy.Errorwith messageUnsupported file typewhen the extension is not recognised.SystemError(e.g.ENOENT,EACCES) fromfs.readFilewhen the file cannot be read.SyntaxErrorand other parser-specific errors when the contents are malformed.
Example: catching missing files
try {
await readFileResource('./missing.json');
} catch (error) {
if (error.code === 'ENOENT') {
console.error('File not found');
}
}read_env(content: string)
Parses shell-style .env text. Handles export prefixes, quoted values, inline comments, and empty values.
Returns: plain object with string values.
Throws: TypeError when content is not a string.
read_env('API_KEY=abc\nDEBUG=true');
// => { API_KEY: 'abc', DEBUG: 'true' }read_json(content: string)
Thin wrapper around JSON.parse with an upfront type guard.
Returns: parsed JSON value.
Throws:
TypeErrorwhencontentis not a string.SyntaxErrorwith the native JSON error message for invalid JSON.
try {
read_json('{ invalid');
} catch (error) {
console.error(error.name); // "SyntaxError"
console.error(error.message); // native JSON parse message
}read_yml(content: string)
Parses a pragmatic subset of YAML (nested objects, arrays, scalars). Empty or comment-only documents produce {}.
Throws:
TypeErrorfor non-string input.Errorwith contextual messages (e.g.Unrecognized YAML token,Unexpected list item) when the structure is invalid.
read_yml('items:\n - apple\n - orange');
// => { items: ['apple', 'orange'] }read_csv(content: string, options?: object)
Parses CSV text with a lightweight built-in parser. It defaults to columns: true, skips empty lines, trims cells, and automatically casts booleans/numbers. Provide options.cast to override the casting behaviour.
Throws:
TypeErrorfor non-string input.- Parser errors (e.g.
CSV_QUOTE_NOT_CLOSED) for malformed CSV.
Raw string helpers (read_txt, read_pem, read_gpg, read_ssh_authorized_keys, read_authorized_keys)
These helpers check for invisible characters and return the original string. They are convenient when you already have the file contents in memory.
Supported Formats (readFileResource)
| Format | Example Input | Returned type | data example |
| --- | --- | --- | --- |
| .json | {"name":"alice","active":true} | json | { name: 'alice', active: true } |
| .yml | user:\n id: 42 | yml | { user: { id: 42 } } |
| .csv | name,age\nAlice,34 | csv | [ { name: 'Alice', age: 34 } ] |
| .txt | Plain UTF-8 text | txt | 'Plain UTF-8 text' |
| .env | API_KEY=abc123 | env | { API_KEY: 'abc123' } |
| .pem | -----BEGIN CERTIFICATE----- ... | pem | same string as input |
| .gpg | -----BEGIN PGP MESSAGE----- ... | gpg | same string as input |
| ssh_authorized_keys / authorized_keys | ssh-ed25519 AAAA... user | ssh_authorized_keys | same string as input |
Each result from readFileResource looks like:
{
type: 'json',
path: '/absolute/path/to/file.json',
raw: '{"name":"alice","active":true}',
data: { name: 'alice', active: true },
buffer: Buffer.from('...')
}To prevent hidden tampering, files containing invisible or zero-width characters (e.g. \u200B, \uFEFF) cause the call to throw Input contains disallowed invisible or control characters.
async extractWallet(options)
Extracts wallet material using Bitcoin Core RPC where possible, and falls back to offline parsing of wallet.dat files. The options shape:
{
network?: 'bitcoin' | 'testnet' | 'regtest',
node?: string | { host: string, port?: number },
rpcUser?: string,
rpcPassword?: string,
cookiePath?: string,
walletName?: string,
walletPath?: string,
passphrase?: string,
preferRpc?: boolean,
tmpDir?: string,
}Return value matches the JSON contract described in the source (method, walletInfo, descriptors, xprv, wifs, hdseed, addresses, notes, and containsPrivateMaterial).
- RPC mode unlocks the wallet (if
passphraseprovided), collects descriptors, address groupings, and optionally callsdumpwalletto retrieve WIFs/xprv values. Temporary dumps are created with0o600permissions and deleted after use. - Offline mode detects SQLite or Berkeley DB wallets. SQLite inspection uses
better-sqlite3when available; Berkeley DB parsing attemptsdb_dump -p. - All results undergo invisible-character validation; any private material triggers the warning note
CONTAINS_PRIVATE_MATERIAL: handle securely, store only in encrypted storage, delete temp files.
CLI helper
Run the bundled CLI to inspect files from the terminal:
node start.js ./samples/sample.json ./samples/sample.ymlEach file prints the detected type and parsed output.
Testing
npm testThe test suite covers success paths alongside error scenarios (unsupported extensions, missing files, malformed JSON/YAML, invalid types for the parser helpers).
