0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Bunで実行バイナリを作る際のバイナリの場所の取得

Posted at

やりたいこと

バイナリの場所を実行時に取得したい!!!

解決策

要約

process.execPath

を使おう!

説明

$ bun build --compile ./index.js

みたいに実行可能バイナリを作るとき、そのバイナリの場所を取得するには process.execPath を使えば取得できる。
これは本来Node本体のパスを取得するものだが、バイナリには bun のランタイムが含まれるため、これで取得出来るらしい。

てっきり __dirname 使うのかと思っていた。

ちなみに __dirname とかは何と驚き コンパイル時にハードコーディングなため、意味がなく(まあ定数と言えば定数なので。あとそもそも非推奨らしいが)、
解決策として提示されている import.meta 系も B:\~BUN\root というよくわからない値を返す。
(たぶんこれはモジュールに対する解決策で、なおかつ __dirname を Node.js 互換にしてほしいという要望なのであまり関係がなさそう。
ちなみにB:\~BUN\ は多分ここから来てる)

検証

> pwd
D:\tmp\bun-dirname\hoge

> bun init 
// index.js
console.log("process.execPath:\t",process.execPath)     // これでやりたいことができる
console.log("import.meta.dir:\t",import.meta.dir)       // 変な値になる(B:\~BUN\root)
console.log("__dirname:\t\t", __dirname)                // 場所はハードコーディング
  • 普通に実行

    > pwd
    D:\tmp\bun-dirname\hoge # 同じディレクトリで
    
    > bun .\index.ts  # 普通に実行
    process.execPath:        D:\Scoop\apps\bun\1.1.42\bun.exe   # Bun 本体のパスが来る(僕はscoopから入れた)
    import.meta.dir:         D:\tmp\bun-dirname\hoge            # ちゃんと正解
    __dirname:               D:\tmp\bun-dirname\hoge            # ちゃんと正解
    
  • コンパイルしてみる

    > pwd 
    D:\tmp\bun-dirname\hoge # ディレクトリ戻って
    
    > bun build --compile .\index.ts    # コンパイル
    [107ms]  bundle  1 modules
    [9.688s] compile  index.exe
    
    > .\index.exe           # 実行
    process.execPath:        D:\tmp\bun-dirname\hoge\index.exe      # あってる(basename やれば同じになる)
    import.meta.dir:         B:\~BUN\root                           # ???
    __dirname:               D:\tmp\bun-dirname\hoge                # あっているように見える
    
  • 場所を移してみる

    > cp .\index.exe ..\index.exe   # ひとつ親にコピー
    
    > cd ..; pwd
    D:\tmp\bun-dirname
    
    > ls
    hoge
    index.exe
    
    > .\index.exe   # 親の方のものを実行
    process.execPath:        D:\tmp\bun-dirname\index.exe       # 追従した
    import.meta.dir:         B:\~BUN\root
    __dirname:               D:\tmp\bun-dirname\hoge           # かわらない
    

おわりに

誰かもっといい方法があれば教えてください。

あと自分の検索力が落ちてきていると感じた。
自分では調べても出てこなかったのに、GPT に聞いたら出てきた...(トホホ...)
(もちろんそれから調べて検証もしているので内容は自分が保証します。何かあったら教えてください。)

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?