Skip to content

Instantly share code, notes, and snippets.

@karvus
Created April 8, 2021 18:00
Show Gist options
  • Save karvus/217f95260c6977b7d0e8cc266c60186f to your computer and use it in GitHub Desktop.
Save karvus/217f95260c6977b7d0e8cc266c60186f to your computer and use it in GitHub Desktop.
const fsPromise = require('fs/promises');
const { tmpdir } = require('os');
const path = require('path');
const { spawn } = require('child_process');
const streamBuffers = require('stream-buffers');
async function jtdToTS(jtdPath) {
let tmpDir = await fsPromise.mkdtemp(`${tmpdir()}${path.sep}`);
let child = spawn('jtd-codegen', [jtdPath, '--typescript-out', tmpDir]);
let errbuf = new streamBuffers.WritableStreamBuffer();
child.stderr.pipe(errbuf);
let promise = new Promise((resolve, reject) => {
child.on('error', (err) => {
fsPromise.rmdir(tmpDir, { recursive: true });
reject(err);
});
child.on('exit', async (code) => {
if (code != 0) {
fsPromise.rmdir(tmpDir, { recursive: true }).catch((err) => {
console.error(err);
});
reject(
`jtd-codegen failed on ${jtdPath}: \n${errbuf.getContentsAsString()}`
);
} else {
let interface = await fsPromise.readFile(
path.join(tmpDir, 'index.ts')
);
fsPromise.rmdir(tmpDir, { recursive: true }).catch((err) => {
console.error(err);
});
resolve(interface);
}
});
});
return promise;
}
@karvus
Copy link
Author

karvus commented Apr 8, 2021

Utility function for facilitating a gulp plugin for jtd-codegen

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment