2
2

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 5 years have passed since last update.

node.js VSCode実行時などでもスクリプトパスを取得する方法

Last updated at Posted at 2018-01-07

少しはまったのでメモしておきます。
環境はWindowsですが、他のOSでも同じかもしれません。

path.js
var path = require('path');
var filePath = process.cwd();
filePath = path.resolve(filePath, './path.js');
console.log(filePath);

これを、コマンド

> node path.js

で、実行すると、正しいパスが得られるのですが、VSCode のF5キーで実行すると、カレントディレクトリが、ホームディレクトリになる様子で、正しいパスになりませんでした。

次のようにすると、実行しているスクリプトファイルのパスが正しく得られます。

path.js
var path = require('path');
var filePath = process.argv[1];
console.log(filePath);

また、path.dirname(filePath); で、親ディレクトリのパスが得られます。

さらには、__dirname には、スクリプトファイルのあるパスが入っています。

参考

node.js で絶対パスや相対パスを取得する方法 npm __dirname · GitHub
https://gist.github.com/uupaa/da42698d6b2d2cbb3cca

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?