How to create a file if it does not exist?



  • Hello, I'm making an application that will have data in JSON and would like to know, how to create a file if it doesn't exist? I'm using the FS.

    Thank you.



  • In the node, you can do the following:

    const fs = require("fs");
    const file = "/home/user/Documents/foo.json";
    

    if (!fs.existsSync(file)) {
    fs.writeFileSync(file, JSON.stringify({hello: "World"));
    }

    The script checks and the file exists and, on the contrary, creates with an illustrative object.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2