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?

More than 3 years have passed since last update.

Node.js 実行中のファイルの絶対パスを取得する。

Posted at

相対パスで指定すると、実行するディクレトリによって結果が変わってしまう。

なので NodeJS のスクリプトの中でのパス指定は絶対パスを使う必要がある。

結論

__dirname を使う。

__dirname は実行中のファイルへの絶対パスを取得できる環境変数。

__dirname is an environment variable that tells you the absolute path of the directory containing the currently executing file.

bin/
 |_ index.js
src/

のようなディレクトリ構成で、index.js から src/ を指定したい場合、

index.js
const srcPath = path.resolve(dirname, '../src')

と指定すると、 node bin/index.js でも、 cd bin/ && node index.js でも同じ結果になる。

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?