Using GLB with textures on node

For those who are looking for the answer to the question about load GLB models on node.js with three.js
Here’s a working solution for models WITHOUT textures:

const toArrayBuffer = (buf) => {
  const arrayBuffer = new ArrayBuffer(buf.length);
  const view = new Uint8Array(arrayBuffer);
  for (let i = 0; i < buf.length; ++i) {
    view[i] = buf[i];
  }
  return arrayBuffer;
}

const loadGLTFModel = (fileName) => {
  const loader = new THREE.GLTFLoader();
  return new Promise((resolve, reject) => {
    if (fs.existsSync(fileName)) {
      const data = fs.readFileSync(fileName);
      const arrayBuffer = toArrayBuffer(data);
      loader.parse(arrayBuffer, '',
        (object3D) => {
          resolve(object3D);
        },
        (error) => {
          console.log(error);
          reject('Loader failed')
        });
    } else reject(`Cannot find ${fileName}`);
  });
}
1 Like