Parsing GLTF file in backend with node.js

I want to find bounding box of glb file &
wan to translate all meshes to center using tranlating all vertices.

When I was trying to do that, I am getting an error

XHR Progress: Error: THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.

Here is my code.

import fs from "fs";
import path from "path";
import * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";

const args = process.argv;
console.log("Arguments:", args);
const glbFile = args[2];

// Check if file exists before reading
fs.stat(glbFile, (err, stats) => {
  if (err) {
    console.error("File does not exist:", glbFile);
    return;
  }
  if (!stats.isFile()) {
    console.error("Provided path is not a valid file:", glbFile);
    return;
  }
  // Read the GLB file (binary data)
  const data = fs.readFileSync(glbFile); // Use readFileSync for binary data
  console.log("Data:", data);
  const loader = new GLTFLoader();
  loader.parse(
    data,
    "",
    (gltf) => {
      console.log("GLTF Loaded Successfully:", gltf);
    },
    (xhr) => {
      console.log("XHR Progress:", xhr);
    },
    (error) => {
      console.error("Error parsing the GLTF:", error);
    }
  );
});

The input to GLTFLoader.parse must be an ArrayBuffer, but readFileSync returns a Buffer (basically a Uint8Array). Instead try:

let data = fs.readFileSync(glbFile);
data = data.buffer.slice(data.byteOffset, data.byteLength);

The slice is necessary because the original ArrayBuffer returned by the fs APIs might be larger than the file itself.


Aside – running GLTFLoader and GLTFExporter in Node.js can be tricky, especially where textures and compression are involved. For the goals you describe, you might consider using glTF Transform instead. See: