Created
April 8, 2021 18:00
-
-
Save karvus/217f95260c6977b7d0e8cc266c60186f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Utility function for facilitating a gulp plugin for
jtd-codegen