node.jsでローカルモジュールを呼び出す時に便利なライブラリ「node-app-root-path」の紹介です。
node.jsでモジュールを使う時は ' require
' メソッドを使って呼び出します。
デフォルトでは ' node_modules
' フォルダからモジュールが呼び出されますが、ローカルモジュール (特定のディレクトリ) を呼び出す時は、相対パス ( ../../ など ) を使います。なので、階層が深い場所からサブディレクト内のファイルを呼び出す時は「いったい今どのパスを参照しているのか。。」とワケが分からなく事もよくあります。
// 相対パスを使ってローカルモジュールを呼び出す例
const Pagination = require("../../Database/Pagination");
const currentPage = require("../../../helpers/pageDetect");
const mobile = require("../../../helpers/detectMobile");
// ------- //
// こんな風にできます
const myDir = require("app-root-path");
const Pagination = require(myDir + "/Database/Pagination");
const currentPage = require(myDir + "/helpers/pageDetect");
const mobile = require(myDir + "/helpers/detectMobile");
そんなパスの分かり辛さを 簡単に解決してくれる node.js用のライブラリが「node-app-root-path」です。
- node.jsでプロジェクトのルートパスを簡単に取得できる

app-root-path は ' npm ' 又は ' yarn ' コマンドを使ってプロジェクトにインストールします。
# npm
npm i -S app-root-path
# yarn
yarn add app-root-path
node-app-rooot-path は ディレクトリに特化した物なので、ライブラリ本体も小さく、プロジェクトを選ばず 汎用的に使えます。
app-root-pathを読み込めば、プロジェクトルートのパスを返します。
const rootDir = require("app-root-path");
// PROJECT_ROOT/helpers/module.jsの読み込み
const helpers = require( rootDir + '/helpers/module' );
' resolve
' メソッドを使えば、フォルダの固定が出来ます。下の例は ' PROJECT_ROOT/helpers
' のパスを返すようにしました。
const helpersPath = require("app-root-path").resolve("helpers");
// PROJECT_ROOT/helpers/module.jsの読み込み
const myModule = require( helperPath + '/module' );
require
オブジェクトを使えば、 ' require
' メソッドを使わず、モジュールを読み込むことが出来ます。
const reqlib = require("app-root-path").require;
// PROJECT_ROOT/helpers/module.jsの読み込み
const helpers = reqlib('/helpers/module');
決まったフォルダのモジュールの テストコードを書く場合に、フォルダ内のファイルを全て読み込む reqire-all
と組み合わせれば、簡単にモジュールを読み込むことが出来ます。
const { test } = use("Test/Suite")("Helpers");
// helpersフォルダ内のコードを一括で読み込み
const helpers = require("require-all")({
dirname: require("app-root-path").resolve("/helpers")
});
test("check base58 test", async ({ assert }) => {
// helpersディレクトからbase58.jsを読み込み
const base58 = helper.base58;
const id = 98999999000000000;
const encode = base58().encode(id);
const decode = base58().decode(encode);
assert.equal(id, decode);
});
以上が node-app-root-path の紹介でした。テストコードを書く時や、モジュールを沢山読み込むプロジェクトで使うと、モジュールを読み込む名前空間の事を気にせずコードを書くことが出来そうです。
GitHub : inxilpro/node-app-root-path