nodejs fs create file if not exists

To create a file if it doesn't already exist using Node.js, you can follow these steps:

  1. Import the fs module: The fs module provides an API for interacting with the file system in Node.js. You can import it using the require keyword:
const fs = require('fs');
  1. Use the fs.existsSync() method to check if the file exists: The existsSync() method of the fs module is a synchronous method that returns true if the specified path exists, and false otherwise. You can pass the file path as an argument to this method:
const filePath = 'path/to/file.txt';
const fileExists = fs.existsSync(filePath);
  1. Create the file if it doesn't exist: If the fileExists variable is false, you can create the file using the fs.writeFileSync() method. This method creates a new file with the specified name and content. You can pass the file path and the content as arguments to this method:
if (!fileExists) {
  const content = 'This is the content of the file.';
  fs.writeFileSync(filePath, content);
}

And that's it! Following these steps will create a file if it doesn't already exist using Node.js.