Home > Blockchain >  having problems with `fs.writeFile` it doesn't create files
having problems with `fs.writeFile` it doesn't create files

Time:02-05

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);
    

CodePudding user response:

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!

  • Related