0
0

関数が呼び出された箇所のディレクトリを取得する方法

Last updated at Posted at 2024-08-28
  • next.jsといったwebページのパスとディレクトリが対応しているフレームワークで、ディレクトリ名を変えると他の箇所も記述を変える必要があるといったことに対応したい

コード

以下を貼り付けて実行すると、この関数が実行されたファイルのディレクトリパスが表示される

// denoならこれ↓を記述
// import * as path from "node:path";
// import * as fs from "node:fs";
import * as path from "path";
import * as fs from "fs";
/*
 * find Directory when you call this function
 */
export const findCurrentDirectory = (): string | undefined => {
  const err = new Error();
  const stack = err.stack?.split("\n") || [];

  // 呼び出し元のスタックトレースを解析して、呼び出し元ファイルのパスを取得
  const callerLine = stack[2]; // スタックの3行目に呼び出し元の情報がある
  const match = callerLine.match(/\((.*):\d+:\d+\)$/);

  if (match) {
    const fullPath = match[1]; // ファイルのフルパス
    const callerDir = path.dirname(fullPath); // ディレクトリ名を取得
    const lastPathSegment = callerDir.split("/").pop(); // 最後のパス部分だけを取得
    return lastPathSegment;
  } else {
    console.log("Could not determine the calling directory.");
  }
};

console.log(findCurrentDirectory());
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0