Euquid Blog.

WEBエンジニアの技術ブログ。主に個人開発で学んだことの備忘録です。

Node.js のpathモジュールでファイルパスの文字列を操作する

Cover Image for Node.js のpathモジュールでファイルパスの文字列を操作する

モジュールの取得

const path = require('path');

使用例

const filePath = '/aaa/bbb/ccc/ddd/index.html';
path.dirname(filePath); // /aaa/bbb/ccc/ddd
path.basename(filePath); // index.html
path.extname(filePath); // .html
path.basename(filePath, path.extname(filePath)); // index

parse でオブジェクトの形でまとめて取得もできる。

path.parse(filePath);
// { root: '/',
//   dir: '/aaa/bbb/ccc/ddd',
//   base: 'index.html',
//   ext: '.html',
//   name: 'index' }

逆に、 format でパスを作ることもできる。

console.log(
  path.format({
    dir: '/aaa/bbb/ccc/ddd',
    base: 'index.html',
  })
);
// /aaa/bbb/ccc/ddd/index.html

参考