How to create a file if it doesn’t exist?

Asked

Viewed 36 times

0

Hello, I am making an application that will have data in JSON and would like to know, how to create a file if it does not exist? I am using FS.

From now on, thank you.

1 answer

0


On 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 otherwise creates with an illustrative object.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.