Skip to content

Instantly share code, notes, and snippets.

@butackle
Created February 19, 2025 13:23
Show Gist options
  • Save butackle/28511bac1dbe59194d5293d7155b0ae5 to your computer and use it in GitHub Desktop.
Save butackle/28511bac1dbe59194d5293d7155b0ae5 to your computer and use it in GitHub Desktop.
Node.jsでファイルパスをOSに応じた書き方にするメモ

内容

Node.jsでファイルパスをOSに応じた書き方にする

ファイルパスの書かれ方は、Windows系かそれ以外(POSIX系?)とかで違う。

# windows
test\\example.txt
# posix
test/example.txt

ので、もし「test/example.txtをWindows形式にしたい」というのがあったら、下記の関数が使える

// posix -> windows
path.win32.normalize("test/example.txt") // test\\example.txt

補足

Node.jsのPathというのはファイルパスを良い感じに操るためのもので、普通にPathを使う際だと下記の感じでwin32などは必要ない。

path.basename('test/example.txt') // example.txt

ただ、Windows系とPOSIX系とでファイルパスの書き方が違うので、 内部的にはpath.win32path.posixが存在しており、実行するOSに応じてpath.win32path.posixを切り替えているらしい。

そういうことなので、path.win32を明示すると、Windows用の関数が使えるということらしい。

なんで

という割に、これは上手くいかなかった

// windows -> posix
path.posix.normalize('test\\example.txt') // test\\example.txt

test/example.txt にしてほしかった。

検証環境

Mac
Node.js v22.13.1

参考

https://nodejs.org/docs/latest-v22.x/api/path.html

すげぇ疲れてるので、テキトーなメモです。正確な書き方をする余力が無かったです。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment