__dirname in ES Modules

TL;DR

import path from "path";
import { fileURLToPath } from "url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

Example Usage

Writing file

const filePath = path.join(__dirname, "hello-world.txt");

fs.writeFileSync(filePath, "Hello, world!");

Check if folder exists

const folderPath = path.join(__dirname, "data");

if (fs.existsSync(folderPath)) {
  console.log("Folder exists");
} else {
  console.log("Folder does not exist");
}

Check if file exists

const filePath = path.join(__dirname, "hello-world.txt");

if (fs.existsSync(filePath)) {
  console.log("File exists");
} else {
  console.log("File does not exist");
}