JavaScript Answers

How to create a file only if it doesn’t exist in Node.js?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *