0

I'm trying to start a script that itself creates a model file in json using fs.writeFile. The problem is when I run the script using node file.js. It is supposed to create a new file face-expression-model.json in directory /models but it doesn't create anything and doesn't show any errors.

I tried to use another library fs-extra not working as well, tried to make the script to create model directory fs.WriteDir not working eitheritried to add process.cwd() to bypass any authorisation when creating the file but didn't work. I also tried to add try/catch block to catch all errors but it doesn't show any errors and it appears that the file was created for the first while but NOPE, unfortunately.

Here is the code I'm using.

const axios = require("axios");
const faceapi = require("face-api.js");
const { FaceExpressions } = faceapi.nets;
const fs = require("fs");

async function trainModel(imageUrls) {
  try {
    await FaceExpressions.loadFromUri(process.cwd() + "/models");

    const imageTensors = [];

    for (let i = 0; i < imageUrls.length; i++) {
      const response = await axios.get(imageUrls[i], {
        responseType: "arraybuffer"
      });

      const image = new faceapi.Image();
      image.constructor.loadFromBytes(new Uint8Array(response.data));

      const imageTensor = faceapi.resizeImageToBase64Tensor(image);

      imageTensors.push(imageTensor);
    }

    const model = await faceapi.trainFaceExpressions(imageTensors);

    fs.writeFileSync("./models/face-expression-model.json", JSON.stringify(model), (err) => {
      if (err) throw err;
      console.log("The file has been saved!");
    });
  } catch (error) {
    console.error(error);
  }
}

const imageUrls = [
    array of images urls here 
];
    

trainModel(imageUrls);
    
Guido
  • 46,642
  • 28
  • 120
  • 174
ImadAris
  • 15
  • 5
  • 1
    `writeFileSync` doesn't have a callback. And if you are already in an `async` context, you shouldn't use it at all. Use `writeFile` from `fs/promises` instead – derpirscher Feb 03 '23 at 22:05
  • 1
    But that there are NO errors and NO file is created, is hard to believe. That would only happen if that method isn't called at all. Can you do a `console.log(path.resolve("./models"))` to verify you are looking in the correct location? – derpirscher Feb 03 '23 at 22:12
  • your first method worked, i jsu had ro use `fs.promises` and removed `Sync` and replaced it with `writeFile`... thanks mate @derpirscher – ImadAris Feb 05 '23 at 00:26

1 Answers1

0

I don't know exactly why but I had the same problem a while ago. Try using the "fs.writeFile" method. It worked for me.

fs.writeFile("models/face-expression-model.json", JSON.stringify(model), {}, (err) => {
  if (err) throw err;
    console.log("The file has been saved!");
});

Good luck with that!