youtube-maze/lib/graphviz.mjs

36 lines
834 B
JavaScript
Raw Normal View History

import { spawn } from 'child_process';
import xml2js from 'xml2js';
const parser = new xml2js.Parser();
const builder = new xml2js.Builder({ headless: true });
const invokeDot = (input, format) => new Promise((resolve, reject) =>
{
const dot = spawn('dot', [`-T${format}`]);
let stdout = '';
dot.stdout.on('data', data => stdout += data);
dot.on('close', code => {
if (code !== 0)
{
reject(new Error(`dot returned error code ${code}`));
}
else
{
resolve(stdout);
}
});
dot.on('error', reject);
dot.stdin.write(input);
dot.stdin.end();
});
export const toSVG = async input =>
{
const svg = await invokeDot(input, 'svg');
const parsed = await parser.parseStringPromise(svg);
return builder.buildObject(parsed);
};