@jirutka/ajv-cli
Version:
CLI for Ajv JSON Schema Validator with human-friendly error messages
36 lines • 1.19 kB
JavaScript
import * as FS from 'node:fs/promises';
import * as path from 'node:path';
import { ProgramError } from '../errors.js';
import * as JSON from './json.js';
import * as YAML from './yaml.js';
export async function parseFile(filepath, fileType) {
const file = await parseFileWithMeta(filepath, fileType);
return file.data;
}
export async function parseFileWithMeta(filepath, fileType) {
const type = fileType || path.extname(filepath).slice(1);
let input;
try {
input = await FS.readFile(filepath, 'utf-8');
}
catch (err) {
throw new ProgramError(err.message, { cause: err, exitCode: 66 });
}
try {
switch (type) {
case 'json':
return JSON.parse(input, filepath);
case 'jsonc':
return JSON.parse(input, filepath, 'jsonc');
case 'yaml':
case 'yml':
return YAML.parse(input, filepath);
default:
throw new Error(`Unsupported file type: ${type}`);
}
}
catch (err) {
throw new ProgramError(`${filepath}: ${err.message}`, { cause: err, exitCode: 65 });
}
}
//# sourceMappingURL=index.js.map