To create a file only if it doesn’t exist in Node.js, we call the readFile
and writeFile
methods.
For instance, we write
import * as fs from "fs";
const upsertFile = async (name) => {
try {
await fs.promises.readFile(name);
} catch (error) {
await fs.promises.writeFile(name, "");
}
};
to define the upsertFile
function.
In it, we call readFile
with the file name
path to check if the file exists.
If it doesn’t exist, an error is thrown and the catch block is run.
In the catch
block, we call writeFile
to write the at the name
path.