diff options
Diffstat (limited to 'src/output.js')
| -rw-r--r-- | src/output.js | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/src/output.js b/src/output.js new file mode 100644 index 0000000..5ab9375 --- /dev/null +++ b/src/output.js @@ -0,0 +1,38 @@ +import fs from 'node:fs'; +import { WaError } from './rpc.js'; +import { format } from './format/index.js'; + +// Parses --params / --json: literal JSON, @file or - (stdin). +export function parseJsonArg(value, flag) { + if (value === undefined) return {}; + let text = value; + try { + if (value === '-') text = fs.readFileSync(0, 'utf8'); + else if (value.startsWith('@')) text = fs.readFileSync(value.slice(1), 'utf8'); + } catch (e) { + throw new WaError('EINVAL', `${flag}: ${e.message}`); + } + try { + return JSON.parse(text); + } catch (e) { + throw new WaError('EINVAL', `${flag}: invalid JSON (${e.message})`); + } +} + +export function print(data, fmt = 'json', { columns, output } = {}) { + let text; + try { + text = format(data, fmt, { columns }); + } catch (e) { + throw new WaError(e.code || 'EINVAL', e.message); + } + if (output) { + fs.writeFileSync(output, text ? `${text}\n` : ''); + } else if (text) { + process.stdout.write(`${text}\n`); + } +} + +export function readStdin() { + return fs.readFileSync(0, 'utf8').replace(/\n$/, ''); +} |