Skip to content

Commit

Permalink
perf: reuse glb instead deleting
Browse files Browse the repository at this point in the history
implements #2
  • Loading branch information
filipemeneses committed Sep 7, 2023
1 parent 8c4e160 commit 972c28d
Showing 1 changed file with 39 additions and 4 deletions.
43 changes: 39 additions & 4 deletions src/unity-to-json/readAndConvertFbxToGltf.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,47 @@
import convert from 'fbx2gltf';
import fs from 'fs/promises';
import fs from 'fs';
import fsPromises from 'fs/promises';
import path from 'path';
import os from 'os';
import crypto from 'crypto';

const getFileHash = (filepath: string) => {
const fd = fs.createReadStream(filepath);

const hash = crypto.createHash('sha1');
hash.setEncoding('hex');

return new Promise((resolve) => {
fd.on('end', () => {
hash.end();
resolve(hash.read());
});
fd.on('error', () => resolve(''));
fd.pipe(hash);
});
};

const silentlyReadFile = async (filepath: string) => {
try {
const result = await fsPromises.readFile(filepath, 'base64');
return result;
} catch (e) {
return '';
}
};

export const readAndConvertFbxToGltf = async (filepath: string) => {
const glbDestPath = path.resolve(os.tmpdir(), `${filepath}.glb`);
const fbxHash = await getFileHash(filepath);
const glbDestPath = path.resolve(os.tmpdir(), `${fbxHash}.glb`);

const recentlyGeneratedGlb = await silentlyReadFile(glbDestPath);
if (recentlyGeneratedGlb) {
return recentlyGeneratedGlb;
}

await convert(filepath, glbDestPath);
const glbBase64 = await fs.readFile(glbDestPath, 'base64');
await fs.unlink(glbDestPath);

const glbBase64 = await fsPromises.readFile(glbDestPath, 'base64');

return glbBase64;
};

0 comments on commit 972c28d

Please sign in to comment.