mirror of
https://github.com/C4illin/ConvertX.git
synced 2026-09-01 15:30:33 +08:00
51 lines
1.3 KiB
TypeScript
51 lines
1.3 KiB
TypeScript
import fs from "fs";
|
|
import { execFile as execFileOriginal } from "node:child_process";
|
|
import { ExecFileFn } from "./types";
|
|
|
|
export const properties = {
|
|
from: {
|
|
document: ["yaml", "toml", "json", "xml", "csv"],
|
|
},
|
|
to: {
|
|
document: ["yaml", "toml", "json", "csv"],
|
|
},
|
|
};
|
|
|
|
export function buildDaselArgs(filePath: string, fileType: string, convertTo: string): string[] {
|
|
return ["--var", `data=${fileType}:file:${filePath}`, "--out", convertTo, "$data"];
|
|
}
|
|
|
|
export async function convert(
|
|
filePath: string,
|
|
fileType: string,
|
|
convertTo: string,
|
|
targetPath: string,
|
|
options?: unknown,
|
|
execFile: ExecFileFn = execFileOriginal, // to make it mockable
|
|
): Promise<string> {
|
|
const args = buildDaselArgs(filePath, fileType, convertTo);
|
|
|
|
return new Promise((resolve, reject) => {
|
|
const childProcess = execFile("dasel", args, (error, stdout, stderr) => {
|
|
if (error) {
|
|
reject(`error: ${error}`);
|
|
return;
|
|
}
|
|
|
|
if (stderr) {
|
|
console.error(`stderr: ${stderr}`);
|
|
}
|
|
|
|
fs.writeFile(targetPath, stdout, (err: NodeJS.ErrnoException | null) => {
|
|
if (err) {
|
|
reject(`Failed to write output: ${err}`);
|
|
} else {
|
|
resolve("Done");
|
|
}
|
|
});
|
|
});
|
|
|
|
childProcess?.stdin?.end();
|
|
});
|
|
}
|