mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-04-24 17:58:27 +02:00
Add ability to select fs.readFile encoding (#267)
This commit is contained in:
@@ -1,17 +1,39 @@
|
|||||||
import type { CallTemplateFunctionArgs, Context, PluginDefinition } from '@yaakapp/api';
|
import type { CallTemplateFunctionArgs, Context, PluginDefinition } from '@yaakapp/api';
|
||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
|
|
||||||
|
const options = [
|
||||||
|
{ label: 'ASCII', value: 'ascii' },
|
||||||
|
{ label: 'UTF-8', value: 'utf8' },
|
||||||
|
{ label: 'UTF-16 LE', value: 'utf16le' },
|
||||||
|
{ label: 'Base64', value: 'base64' },
|
||||||
|
{ label: 'Base64 URL-safe', value: 'base64url' },
|
||||||
|
{ label: 'Latin-1', value: 'latin1' },
|
||||||
|
{ label: 'Hexadecimal', value: 'hex' },
|
||||||
|
];
|
||||||
export const plugin: PluginDefinition = {
|
export const plugin: PluginDefinition = {
|
||||||
templateFunctions: [
|
templateFunctions: [
|
||||||
{
|
{
|
||||||
name: 'fs.readFile',
|
name: 'fs.readFile',
|
||||||
description: 'Read the contents of a file as utf-8',
|
description: 'Read the contents of a file as utf-8',
|
||||||
args: [{ title: 'Select File', type: 'file', name: 'path', label: 'File' }],
|
args: [
|
||||||
|
{ title: 'Select File', type: 'file', name: 'path', label: 'File' },
|
||||||
|
{
|
||||||
|
title: 'Select encoding',
|
||||||
|
type: 'select',
|
||||||
|
name: 'encoding',
|
||||||
|
label: 'Encoding',
|
||||||
|
defaultValue: 'utf8',
|
||||||
|
description: 'Specifies how the file’s bytes are decoded into text when read',
|
||||||
|
options,
|
||||||
|
},
|
||||||
|
],
|
||||||
async onRender(_ctx: Context, args: CallTemplateFunctionArgs): Promise<string | null> {
|
async onRender(_ctx: Context, args: CallTemplateFunctionArgs): Promise<string | null> {
|
||||||
if (!args.values.path) return null;
|
if (!args.values.path || !args.values.encoding) return null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return fs.promises.readFile(String(args.values.path ?? ''), 'utf-8');
|
return fs.promises.readFile(String(args.values.path ?? ''), {
|
||||||
|
encoding: String(args.values.encoding ?? 'utf-8') as BufferEncoding,
|
||||||
|
});
|
||||||
} catch {
|
} catch {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user