Loading GLTF models in Nodejs

Hi everyone,

Sharing the following node setup. Hope is saves you some time :slight_smile:

Use case? Needed this setup for unit testing.

//package.json
  "devDependencies": {
    "xhr2": "^0.2.1"
  },
  "dependencies": {
    "@babylonjs/core": "^6.5.0",
    "@babylonjs/loaders": "^6.5.0"
  }

//or
//npm install @babylonjs/core
//npm install @babylonjs/loaders
//npm install @xhr2
//file.js
import * as BABYLON from "@babylonjs/core";
import "@babylonjs/loaders";
import XMLHttpRequest from 'xhr2';

//test setup
global.XMLHttpRequest = XMLHttpRequest;

//test
var gltf = `data:{ ... }`;
await BABYLON.SceneLoader.AppendAsync("", gltf, scene);
console.log( scene.getMeshByName("UnitTestCubeWDirs") )

Best wishes
Joe

4 Likes

Thanks, I bet it can help !!!

Thanks for sharing with the community!

If you want to load GLB files, same as above but

import { readFile } from 'node:fs/promises';

async function loadModel(filePath : string, scene : Scene) {
    const glb = await readFile(filePath, {encoding: 'base64'});
    await SceneLoader.AppendAsync("", "data:;base64," + gltf, scene);
}

Notice the base64 stuff!

4 Likes

I haven’t tried it in a node environment, but we support loading ArrayBufferView now, so it should be possible to skip the base64 step which should improve performance.

2 Likes